0

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?

1
  • Sounds like homework. If it is so, please tag it accordingly. Commented Apr 22, 2011 at 12:52

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.