bremmS
bremmS

Reputation: 277

Weird outputs while using DataOutputStream

I'm using DataOutputStream of Java IO in order to write to a file but when I execute the program, I don't get the correct output, instead, I get weird characters. -Although I have noticed that only writing strings using the writeUTF(String str) method works, even using writeBytes(String s) produces a weird character that's supposed to be space character- The code part of writing to file is below, any ideas on possible causes, maybe something related to encodings? Thanks in advance.

FileOutputStream fs= new FileOutputStream("Path/to/my/file");

DataOutputStream ds = new DataOutputStream(fs);


ds.writeBoolean(false);
ds.writeChar('A');
ds.writeInt(42);
ds.writeBytes("test1");
ds.writeUTF("test2");


fs.close();

Upvotes: 1

Views: 1715

Answers (2)

confucius
confucius

Reputation: 13327

Data Streams are for binary data DataOutputStream writing the integer in binary format, i.e. it splits the integer into 4 bytes and writes those

Upvotes: 1

Roland Illig
Roland Illig

Reputation: 41625

The DataOutputStream class is defined to write a stream of bytes, not a stream of characters. This stream of bytes has the purpose of being efficiently and portably stored, no matter whether humans can read it or not.

If you want human-readable text files, use an XML writer.

By the way, the output you get is correct, it's rather your understanding that is wrong. You probably just need to read and understand the documentation that comes with the class.

Upvotes: 2

Related Questions