What is the Difference between PrintWriter and DataOutputStream?

后端 未结 3 1034
天涯浪人
天涯浪人 2020-12-30 13:21

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

3条回答
  •  一向
    一向 (楼主)
    2020-12-30 13:57

    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();
    

提交回复
热议问题