Reputation: 353
Explain the difference between the outputs of the following two fragments of code for outputting an int i to a file:
i)
PrintWriter outfile = new PrintWriter(new FileWriter("ints.txt"));
outfile.print(i);
ii)
DataOutputStream out = new DataOutputStream(new FileOutputStream("ints.dat"));
out.writeInt(i);
I think the Printer writer takes a string and tranforms it into a stream of unicode characters, whereas dataoutput stream converts the data items to sequence of bytes.
What more would you add?
Upvotes: 0
Views: 310
Reputation: 6124
possibly repeating what was already said, but just to make it more explicit:
when you use a printwriter, and say you have an int value of 65 -- the print writer will print 2 characters: '6' and '5'
when you use an outputstream, this prints bytes so it will write to the file a byte with the value of 65 -- this happens to be the character code in ASCII/UTF-8 for 'A' so if you open up the file in a text editor you will see an "A" character -- rather than '6' followed by '5' as above.
Upvotes: 0
Reputation: 13564
From DataOutputStream
javadoc:
A data output stream lets an application write primitive Java data types to an output stream in a portable way. An application can then use a data input stream to read the data back in.
From PrintWriter
javadoc
Prints formatted representations of objects to a text-output stream.
Everything is just bytes, but they represent different things. With a DataOutpuStream
you get bytes that you can read back directly to your primitive Java type int
, whereas with a PrintWriter
you don't.
Upvotes: 1
Reputation: 533432
Files only contain byte, so it all ends up as bytes in the end.
A String is already a stream of characters. When you write a String to a file it has to turn it into a stream of bytes.
An int is four bytes. writeInt() turns it into a big endian number.
Upvotes: 1