Hi all: I am using the below code to write a string in to a file in Linux. //********** DataOutputStream outputStream; outputStream = new DataOutputStream(new FileOutputStream(HomeDir + "/state.txt")); outputStream.writeUTF("Hey asfssa"); outputStream.close(); //******* the file is created and no exception is thrown. However, upon opening the file, i see that the string is preceded by a few junk charecters. Why does this happen. Also, i am not able view the file in the application gedit but vi shows me the data along with the junk. Appreciate the help. Thanks, Preetham M
Joined: Jul 24, 2002
Did you read the javadoc for DataOutputStream.writeUTF ? It tells you what it is going to write.
First, two bytes are written to the output stream as if by the writeShort method giving the number of bytes to follow. This value is the number of bytes actually written out, not the length of the string. Following the length, each character of the string is output, in sequence, using the UTF-8 encoding for the character.
Are you seeing "junk", are are you seeing the binary representation of a short integer describing the length of the output?
Joined: Jan 30, 2000
Generally, DataOutputStream is used for writing binary files (which will probably be read by a DataInputStream). If you want to make a text file (i.e. one that you can open with a text editor and see understandable characters) you should probably use a Writer of some sort. Most likely a FileWriter wrapped with a BufferedWriter. Or maybe also wrapped with a PrintWriter.
"I'm not back." - Bill Harding, Twister
Joined: Sep 18, 2002
yeah, the junk looks like the first two bytes which specify the length. Thanks, i used writeBytes() and that got rid of the junk.