In java.io.RandomAccessFile , when the method writeChar() is used to write a char array in loop to a Text file as
RandomAccessFile txtfile = new RandomAccessFile("Hello.txt","rw");
char c[] = {'S','i','g','n','e','d'};
for(char k:c) txtfile.writeChar(k);
Gives a Result in Hello.txt as when opened in normal notepad
S i g n e d
but , when opened with text Editor NotePad++ the Hello.txt is shown as
[NUL]S[NUL]i[NUL]g[NUL]n[NUL]e[NUL]d
and when i used writeUTF() method to write a String to Hello.txt as
txtfile.writeUTF("hello");
it given result as a blank space in front and when opened in NotePad++ it is showing as
[ENQ]hello
How i can write or append a Normal Line to file with out Spaces(like [NUL] or [ENQ] ) as in this case ?
please post answer how to write any String to a file in RandomAccessFile in Java !
Thanks in Advance !
A char
value in Java is two bytes. RandomAccessFile
is meant to read and write binary data. It does not do any text transformations. When asked to write a character, it just writes the in-memory representation of that character to disk.
Look at the documentation for the RandomAccessFile
class:
writeChar(int v)
- Writes a char to the file as a two-byte value, high byte first.
writeByte(int v)
- Writes a byte to the file as a one-byte value.
writeBytes(String s)
- Writes the string to the file as a sequence of bytes.
So use writeByte
instead of writeChar
to write a character to the file as a single ASCII byte that all editors should deal with in the same way.
To write a String to the file as single-byte characters in one call, use the writeBytes
method, which takes a String and writes it to the file as single-byte characters.
If you only want to write text to a file, it's better to use a FileWriter
or OutputStreamWriter
class to do so. These classes write text taking character encoding into account. The former assumes a default character encoding. The latter allows you to specify the character encoding you want the class to use to convert text to bytes before writing to the file.