Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Difference between PrintWriter and DataOutputStream?

Tags:

java

android

chat

I'm working on a chat room application for android. I read different tutorials; some of them use PrintWriter to send data and some of them use DataOutputStream. What is the difference between these two? Which one is better for a chat app?

like image 638
pouyan Avatar asked Jun 27 '13 14:06

pouyan


2 Answers

From java docs

A DataOutputStream 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.

PrintWriter Prints formatted representations of objects to a text-output stream. This class implements all of the print methods found in PrintStream. It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.

In one sentence the difference is:

OutputStreams are meant for binary data. Writers (including PrintWriter) are meant for text data

like image 144
Juned Ahsan Avatar answered Oct 24 '22 06:10

Juned Ahsan


PrintWriter converts everything to Ascii format. For example:

PrintWriter pw = new PrintWriter(new File("./test.txt"));        
        for (Integer word: words) {
            pw.println(word);
        }

in this block of code, by calling pw.printin(word); no matter what the type of word is (which is integer here), program converts it to ASCII format and stores it. As a result, when we want to retrieve that stored data and read it again, program have to do another type changing from text to original format! -which is not good in term of time efficiency! For instance, if that word is an integer, after storing that into a file (which is text now), program has to change its format from String to integer when it is going to retrieve that!

But, DataOutPutStream makes everything much easier since it stores the data into bytes by keeping data type. So, when we run bellow block, program stored integer as byte and when it want to retrieve that it does not need any change of type. It's stored as integer and retrieved as integer too. So, it is much faster!

DataOutputStream dos = new DataOutputStream(
            new FileOutputStream(new File("test2.txt")));

    for (Integer word: words) {
        dos.writeUTF(word);   
 }
dos.close();
like image 45
Reihan_amn Avatar answered Oct 24 '22 06:10

Reihan_amn