Java write byte in file

I am making a Comprimir file for a binary file in Java. The problem is this: how can I write a byte in a new file so that the total size is only 1 byte? I do the following:

FileOutputStream saveFile=new FileOutputStream("SaveObj3.sav"); // Create an ObjectOutputStream to put objects into save file. ObjectOutputStream save = new ObjectOutputStream(saveFile); save.writeByte(0); save.close(); saveFile.close(); 

This is only necessary to write only one byte to a file, but when I look at the size, it takes 7 bytes. Does anyone know how I can write only bytes? Is there any other way better?

+4
source share
3 answers

Do not use ObjectOutputStream . Use FileOutputStream directly:

 FileOutputStream out=new FileOutputStream("SaveObj3.sav"); out.write(0); out.close(); 
+2
source

As JB Nizet noted, the documentation of the ObjectOutputStream constructor states that this object is also

writes the header of the serialization stream to the base stream

which explains the extra bytes.

To prevent this behavior, you can simply use other streams like FileOutputStream or possibly DataOutputStream

 FileOutputStream saveFile = new FileOutputStream("c:/SaveObj3.sav"); DataOutputStream save = new DataOutputStream(saveFile); save.writeByte(0); save.close(); 
+3
source

You can use the file class provided by Java 7. This is easier than expected.

It can be executed in one line:

 byte[] bytes = new String("message output to be written in file").getBytes(); Files.write(Paths.get("outputpath.txt"), bytes); 

If you have a File class, you can simply replace:

 Paths.get("outputpath.txt") 

in

 yourOutputFile.toPath() 

To write only one byte as you want, you can do the following:

 Files.write(Paths.get("outputpath.txt"), new byte[1]); in file properties: size: 1 bytes 
+1
source

Source: https://habr.com/ru/post/1483946/


All Articles