(Java) 将十进制/十六进制写入文件,而不是字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1388383/
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
(Java) Write decimal/hex to a file, and not string
提问by Tony Stark
If I have a file, and I want to literally write '42' to it (the value, not the string), which for example is 2a in hex, how do I do it? I want to be able to use something like outfile.write(42) or outfile.write(2a) and not write the string to the file.
如果我有一个文件,并且我想从字面上写 '42'(值,而不是字符串),例如 2a 的十六进制,我该怎么做?我希望能够使用类似 outfile.write(42) 或 outfile.write(2a) 的东西,而不是将字符串写入文件。
(I realize this is a simple question but I can't find the answer of google, probably because I don't know the correct search terms)
(我意识到这是一个简单的问题,但我找不到谷歌的答案,可能是因为我不知道正确的搜索词)
回答by Joachim Sauer
For writing binary data you'll want to use a OutputStream(such as a FileOutputStream).
要写入二进制数据,您需要使用 a OutputStream(例如 a FileOutputStream)。
If you find that your data is written as strings, then you're probably using a Writer(such as a FileWriteror a OutputStreamWriterwrapped around a FileOutputStream). Everything named "*Writer" or "*Reader" deals exclusively with text/Strings. You'll want to avoid those if you want to write binary data.
如果您发现您的数据是作为字符串写入的,那么您可能正在使用 a Writer(例如 aFileWriter或 aOutputStreamWriter环绕的 a FileOutputStream)。名为“ *Writer”或“ *Reader”的所有内容都专门处理 text/ Strings。如果你想写二进制数据,你会想要避免这些。
If you want to write different data types (and not just plain bytes), then you'll want to look into the DataOutputStream.
如果您想编写不同的数据类型(而不仅仅是普通的bytes),那么您需要查看DataOutputStream.
回答by ZZ Coder
OutputStream os = new FileOutputStream(fileName);
String text = "42";
byte value = Byte.parseByte(text);
os.write(value);
os.close();
回答by vpram86
回答by Stephen C
If you justwant to write bytes, the following will suffice:
如果您只想写入字节,则以下内容就足够了:
import java.io.*;
...
OutputStream out = new FileOutputStream("MyFile");
try {
// Write one byte ...
out.write((byte) 42);
// Write multiple bytes ...
byte[] bytes = ...
int nosWritten = out.write(bytes, 0, bytes.length);
} finally {
out.close();
}
Exception handling is left as an exercise for the reader :-)
异常处理留给读者作为练习:-)

