简体   繁体   中英

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

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.

在此处输入图片说明

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM