javadataoutputstreamfilestreams

Issue with FileOutputStream and DataOutput Stream


The problem is when I write a character using FileOutputStream it is readable. But when I chain it with DataOutputStream the written data becomes unreadable.

Why is that ? Since both FileOutputStream and DataInputStream write in bytes to the file. How exactly will the processing happen ?

Code:

File newFile = new File("C:\\Jeevantest.as");
FileOutputStream outFp = new FileOutputStream(newFile);
outFp.write('X');
outFp.close();

In the file Jeevantest.as, the char 'X' can be seen. 

File newFile = new File("C:\\Jeevantest.as");
FileOutputStream outFp = new FileOutputStream(newFile);
DataOutputStream dp = new DataOutputStream(outFp);
dp.writeChar('J');
outFp.close();

In this case, the following output is shown:

Output

Need to understand why ?


Solution

  • The difference resides not in the OutputStreams but in the write methods you are using: they differ. In your first example you use dp.write() and in your second example you use dp.writeChar().

    Change dp.writeChar() to dp.write() in your second example and the results will be as expected.

    java.io.DataOutputStream.writeChar(int) method is implemented as follows:

    public final void writeChar(int v) throws IOException {
        out.write((v >>> 8) & 0xFF);
        out.write((v >>> 0) & 0xFF);
        incCount(2);
    }
    

    See soource code of writeChar(int)

    while java.io.DataOutputStream.write(int) has following implementation:

     public synchronized void write(int b) throws IOException {
         out.write(b);
         incCount(1);
     }
    

    See soource code of write(int)