Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

ObjectOutputStream.writeUTF Producing Junk Characters 1

Status
Not open for further replies.

BoulderBum

Programmer
Jul 11, 2002
2,179
US
It seemed simple enough. All I wanted to do was write a bunch of strings to a text file, and it sort of works, but when I open the file, there are junk characters in front of all my strings.

It's like square, square, 'W', square.

Anyone know what's going on?

Here's the code:

output.writeUTF( "test\n" );//(String) ResultsStringsArray.get(i) );
output.flush();
 
I imagine the below answers your question ! If you are using methods you are not familiar with, it always helps to read the docs first ...


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 modified UTF-8 encoding for the character. If no exception is thrown, the counter written is incremented by the total number of bytes written to the output stream. This will be at least two plus the length of str, and at most two plus thrice the length of str.
 
I actually did check the docs (that's how I found out about the method to begin with), but I stopped here:

writeUTF(String str)
Writes a string to the underlying output stream using Java modified UTF-8 encoding in a machine-independent manner.


I guess I assumed too much in thinking the summary covered it, but I tend to do things like that when I'm on insomniac code-writing marathons.

I ended up going with a BufferedWriter chained to FileWriter to avoid printed size info. Is that the best way?
 
Yeah, thats a fairly good way ... using the Buffered* streams is good practice. I personally tend to use BufferedOutputStream, and use the write(byte[], off, length) method, as it will the pure byte data, not just ascii ...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top