sagar
sagar

Reputation: 745

DataOutputStream not generating bytes as output?

DataOutputStream Class is used to write the primitive data types as binary format. I have been using the methods void writeChars(String s) of DataOutputStream class,to write it in a file using the program...

public class FileDemo {
    public static void main(String[] args) throws IOException{
        String x= "haha";
        DataOutputStream out = new DataOutputStream(new FileOutputStream("E:/a.txt"));
        out.writeChars(x);
        out.close();
    }
}

The file a.txt now has the following text as output(all chars separated by space):

 h a h a

My question is why does the file not having the string as bytes?? And please also explain that why there is a need to use PrintWriter when we can use functions of DataOutputStream to write all primitives...

Upvotes: 0

Views: 153

Answers (2)

René Link
René Link

Reputation: 51363

The DataOutputStream does exactly what it is for. It writes the chars as bytes. One char is made up of two bytes.

So it writes the chars haha as bytes

0, 104, 0, 97, 0, 104, 0 ,97

because char h is represented as the two bytes 0, 104.

When you open the file in your text editor it tries to interprete the bytes according to a specified encoding. Notepad for example will use ANSI by default.

If you open the file in Notepadd++ it can shows you the 0 bytes.

enter image description here

Use an OutputStreamWriter if you want the char to be converted to the byte representation of a defined encoding. E.g.

OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(
            "C:/Dev/a.txt"), Charset.forName("windows-1252"));
out.write(x);
out.close();

This will output the bytes

104, 97, 104, 97

Upvotes: 1

Roshith
Roshith

Reputation: 2175

Are you looking for writeBytes(s) ? Or are you wondering why the file doesn't contain something like 1010101010 ?

Upvotes: 0

Related Questions