I know this is not the best way to deal writing and reading text from a file ( should buffer stuff or use FileReader/Writer etc ) but I'm trying to understand what is going on here.
So I have this straight, all information when written to a file is just really a stream of bytes written to the file. So that when you use DataInputStream and the various readXXX methods you are just reading back the correct number of bytes needed to make the XXX datatype. If this is the case what am I doing wrong, or how come in the following code I wrote when I do writeBytes(
String s) versus writeChars(String s ) I get back a bunch of question marks when I read from the file using a loop and doing readChar() ? I would think that readChar() wouldn't care how the bytes were written to the file. Possibly though the problem is in using writeBytes( Sting s )? Maybe when you do writeBytes( String s ) it's not writing the 2 byte representation of the chars to the file? I'm a bit confused here.
Also, what is wrong with my construct in the while loop for getting back the chars? Is there no way around it throwing at a EOFException when it gets to the end? ( I know this should be buffered in a BufferedOutputStream, etc. but I'm trying to get some of these basics understood).
Thanks for any help.
and if you want it without the UBB code for cut and paste help:
import java.io.*;
class TestIOStuff {
static char c;
public static void main( String[] args ) throws IOException {
String s = "Some boring String Line";
File file = new File("testing.txt");
FileOutputStream fo = new FileOutputStream( file );
DataOutputStream out = new DataOutputStream( fo );
out.writeChars( s );
//out.writeBytes( s );
out.close();
FileInputStream fi = new FileInputStream( file );
DataInputStream in = new DataInputStream( fi );
try {
while( (c = in.readChar()) != -1 ) {
System.out.print( c );
}
}
catch( Exception e ) {
System.out.println( "\n"+e );
}
in.close();
}
}