java 如何在Java中将二进制数据写入文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25272184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write binary data into files in Java?
提问by Ramses Asmush
Is there a way to store some values in a binary file as C# does?
有没有办法像 C# 那样在二进制文件中存储一些值?
For example in C# it would be:
例如在 C# 中,它将是:
BinaryWriter bw = new BinaryWriter(MyFilStream);
bw.Write(data...);
And then, to read it like
然后,阅读它
BinaryReader br = new bla bla...;
br.ReadInt(file);
Is there a way to do this in Java? I'm Reading a lot of binary reading in Google, but I just find something of a JPG file, don't get it...
有没有办法在 Java 中做到这一点?我在谷歌中阅读了很多二进制阅读,但我只是找到了一些 JPG 文件,不明白......
回答by IhsanC
You could make use of DataOutputStream
and/or DataInputStream
to store and read binary data in Java.
您可以使用DataOutputStream
和/或DataInputStream
在 Java 中存储和读取二进制数据。
Here is an example of how it's done:
这是一个如何完成的示例:
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(); }
编者注:
.close()
语句应该包装在finally
块中:finally { d.close(); out.close(); }
Source:
http://www.tutorialspoint.com/java/java_dataoutputstream.htm
来源:http:
//www.tutorialspoint.com/java/java_dataoutputstream.htm