简体   繁体   中英

DataOutputStream only writes a string Java

DataOutputStream dataOut = new DataOutputStream(new FileOutputStream("myfile.txt"));
dataOut.writeUTF("HEY");   // write HEY
dataOut.writeShort(1);     // writes nothing

I am trying to use DataOutputStream to write something in my text file. However, it only writes a string, not an integer or short. I do not understand why it only writes strings. Please help.

NOTE: Despite calling the file myfile.txt , this is a binary not a text format so you can't expect to read it as text eg with a text editor and see the short value.

This works fine if you close the file and read it the same way it was written.

try (DataOutputStream dataOut = new DataOutputStream(new FileOutputStream("myfile.txt"))) {
    dataOut.writeUTF("HEY");   // write HEY
    dataOut.writeShort(1);
}
try (DataInputStream dataIn = new DataInputStream(new FileInputStream("myfile.txt"))) {
    System.out.println("string: " + dataIn.readUTF());
    System.out.println("short: " + dataIn.readShort());
}

prints

string: HEY
short: 1

Most likely you expected the file to be text.

try (PrintWriter dataOut = new PrintWriter(new FileOutputStream("myfile.txt"))) {
    dataOut.println("HEY");   // write HEY
    dataOut.println(1);
}
try (Scanner dataIn = new Scanner(new FileInputStream("myfile.txt"))) {
    System.out.println("string: " + dataIn.nextLine());
    System.out.println("short: " + dataIn.nextShort());
}

prints

string: HEY
short: 1

and the file contains

HEY
1

You have produced no evidence for your assertion. Neither writeUTF() nor writeInt() produces text. They both produce binary data. You should not try to save this data in a file with the .txt extension (and you should not try to read it with a text editor). The only way you can read this data is with a DataInputStream .

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