简体   繁体   English

Java在文件中写入字节

[英]Java write byte in file

I am doing in Java a File Comprimir to a Binary File. 我在Java中使用二进制文件的文件Comprimir。 The problem is the next, how can I write a Byte in a new File that the total size only occups 1 byte? 问题是下一步,如何在新文件中写一个字节,总大小只占1个字节? I am doing the next: 我正在做下一个:

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();

That, only must to write a only byte in the file, but when I look the size,it occups 7 bytes. 那,只需要在文件中写一个唯一的字节,但是当我查看大小时,它会占用7个字节。 Anyone knows how can I write a only byte? 任何人都知道如何写一个唯一的字节? Is there another way better? 有另一种方式更好吗?

Don't use ObjectOutputStream . 不要使用ObjectOutputStream Use the FileOutputStream directly: 直接使用FileOutputStream

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

As JB Nizet noticed documentation of ObjectOutputStream constructor states that this object also 正如JB Nizet注意到ObjectOutputStream构造函数的文档也说明了这个对象

writes the serialization stream header to the underlying stream 将序列化流标头写入基础流

which explains additional bytes. 这解释了额外的字节。

To prevent this behaviour you can just use other streams like FileOutputStream or maybe DataOutputStream 要防止此行为,您可以使用其他流,如FileOutputStreamDataOutputStream

FileOutputStream saveFile = new FileOutputStream("c:/SaveObj3.sav");
DataOutputStream save = new DataOutputStream(saveFile);

save.writeByte(0);

save.close();

You can use Files class provided by Java 7. It's more easy than expected. 您可以使用Java 7提供的Files类。它比预期的更容易。

It can be performed 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 just replace: 如果您有File类,则只需替换:

Paths.get("outputpath.txt")

to: 至:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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