This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
hi all, i've a problem about writeUTF method of DataOutputStream. i was trying to write the text from a textarea into a file, and later retrieving the text from that file line by line by using RandomAccessFile, and separate the line into tokens of string by using StringTokenizer.
however, it seems like that when i write the text like "a,b,1,2" to a file, the actual file becomes sth like " a,b,1,2" (or "*a,b,1,2" or "->a,b,1,2" when i print it to the system.out). so i always get ClassFormatError in runtime when i was trying to tokenize the first character. i dont know what caused it like that. is it because of the writeUTF method itself? if so, is there any way that i can get rid of the leading space? (i wish i could use sed/tr, but unfortunately i can't )
writeUTF first writes a short to the stream to indicate how many bytes (not characters!!!) are following.. That's maybe your problem... However, you should consider using the paired DataInputStream/DataOutputStream to read/write your streams since they are meant to be used together... But if you stay like that, you can just read the first short (2 bytes) and then your string... The bad thing is that you don't really know what to read with your RandomAccessFile since UTF uses a weird encoding technique with variable sized bytes. [ February 20, 2002: Message edited by: Valentin Crettaz ]
thanks valentin for the hints. this place is amazing. i'll try to use DataInputStream instead of RandomAccessFile to read the file. as i may still need to use readUTF,i should be very careful. (i was trying to use writeChar/writeByte from a textarea, but it didnt work. but i may be able to retrive a file into an array(not a textarea) by using readChar or readByte) will it be more convinient to use Reader/Writer for the purpose of data tokenizing later on? anyway i'll try both.
Joined: Aug 26, 2001
Reader and Writers are especially useful when dealing with character data and not raw bytes. You should try to use them. Remember that the *Input/OutputStream classes should be used in pairs, otherwise you might get unexpected results...
Joined: Dec 16, 2001
does that mean if i'm dealing with String, use Reader/Writer, and if dealing with primitive datatypes, use InputStream/OutputStream? oh, that's why there're read/writeByte, Char, etc methods in InputStream/OutputStream. that makes sense.