有没有办法像 C# 那样在二进制文件中存储一些值?
例如,在 C# 中,它是:
BinaryWriter bw = new BinaryWriter(MyFilStream);
bw.Write(data...);
然后,读起来像
BinaryReader br = new bla bla...;
br.ReadInt(file);
有没有办法在Java中做到这一点?我在Google上读了很多二进制读物,但我只是找到了一些JPG文件,不明白......
最佳答案
您可以使用DataOutputStream
和/或DataInputStream
在Java中存储和读取二进制数据。
以下是如何完成的示例:
import java.io.*;
public class Test{
public static void main(String args[])throws IOException{
DataInputStream d = new DataInputStream(new
FileInputStream("test.txt"));
DataOutputStream out = new DataOutputStream(new
FileOutputStream("test1.txt"));
String count;
while((count = d.readLine()) != null){
String u = count.toUpperCase();
System.out.println(u);
out.writeBytes(u + " ,");
}
d.close();
out.close();
}
}
Editors' note:
.close()
statements should be wrapped infinally
block:finally { d.close(); out.close(); }
Source:
http://www.tutorialspoint.com/java/java_dataoutputstream.htm
关于java - Java中如何将二进制数据写入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25272184/