Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

DataOutputStream along with some Garbage

 
Preetham M
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Dave Landers
Ranch Hand
Posts: 401
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Preetham M
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yeah, the junk looks like the first two bytes which specify the length.
Thanks, i used writeBytes() and that got rid of the junk.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic