Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why does the file content created by RandomAccessFile.writeType method look weird

 
Judy YU
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I compiled and ran the following program:
import java.io.*;
public class Random {
public static void main(String[] args) throws IOException {
RandomAccessFile file = new RandomAccessFile("text", "rw");
file.seek(file.length() );
file.writeChars("after file");
file.writeInt(1);
}
}
The "text" file is previously present in the current directory, and it contains follows content afterwards:
^@a^@f^@t^@e^@r^@ ^@f^@i^@l^@e^@a^@f^@t^@e^@r^@ ^@f^@i^@l^@e^@^@^@^A
Why ? It doesn't look like byte representation of the String and int either?
Can somebody explain to me? How can we write to a file with normal looking content? Thanks.
 
Carl Trusiak
Sheriff
Posts: 3341
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'd like to know what software you are viewing this with. Basically writeChars writes the String as a series of writeChar() which writes a single 2 byte character to the stream. This is the Unicode value so, the first byte for the characters in your String is always 0. Whatever you are using to display this is showing the 0 as ^@. If you would view this information with a hex editor such as UltraEdit in Hex mode you would see:
00 61 00 66 00 74 00 65 00 72 00 20 00 66 00 69 00 6C 00 65 .a.f.t.e.r. .f.i.l.e
Hope this helps
 
Weigang Gu
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I run your program and get a very different result.
nothing written to "text"
when I use writeUTF("after file"):
only "after file" was written to "text";
sometimes with a blank line added/but not consistent;
no int was ever written to the file;
the file length did increase after writing int;

anybody any thoughts about it?
Originally posted by Judy YU:
I compiled and ran the following program:
import java.io.*;
public class Random {
public static void main(String[] args) throws IOException {
RandomAccessFile file = new RandomAccessFile("text", "rw");
file.seek(file.length() );
file.writeChars("after file");
file.writeInt(1);
}
}
The "text" file is previously present in the current directory, and it contains follows content afterwards:
^@a^@f^@t^@e^@r^@ ^@f^@i^@l^@e^@a^@f^@t^@e^@r^@ ^@f^@i^@l^@e^@^@^@^A
Why ? It doesn't look like byte representation of the String and int either?
Can somebody explain to me? How can we write to a file with normal looking content? Thanks.

 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic