File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes DataOutputStream along with some Garbage Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "DataOutputStream along with some Garbage" Watch "DataOutputStream along with some Garbage" New topic

DataOutputStream along with some Garbage

Preetham M

Joined: Sep 18, 2002
Posts: 12
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");
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.
Preetham M
Dave Landers
Ranch Hand

Joined: Jul 24, 2002
Posts: 401
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

Joined: Jan 30, 2000
Posts: 18671
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
Preetham M

Joined: Sep 18, 2002
Posts: 12
yeah, the junk looks like the first two bytes which specify the length.
Thanks, i used writeBytes() and that got rid of the junk.
I agree. Here's the link:
subject: DataOutputStream along with some Garbage
jQuery in Action, 3rd edition