如何用Java将二进制文件写入文件 [英] How to write binary to a file in Java
问题描述
我正在尝试从文件获取输入,将字符转换为二进制,然后将二进制输出到另一个输出文件.
I am trying to get input from a file, convert the characters to binary and then output the binary to another output file.
我使用Integer.toBinaryString()进行转换.
I used Integer.toBinaryString() in order to make the conversion.
一切正常,但由于某种原因,没有任何内容写入输出文件,但是当我使用System.out.println()时,它可以正常输出.
Everything is working as it should but for some reason nothing is written to the output file, but when I use System.out.println() it outputs fine.
import java.io.*;
public class Binary {
FileReader fRead = null;
FileWriter fWrite = null;
byte[] bFile = null;
String fileIn;
private String binaryString(int bString) {
String binVal = Integer.toBinaryString(bString);
while (binVal.length() < 8) {
binVal = "0" + binVal;
}
return binVal;
}
public void input() throws IOException, UnsupportedEncodingException {
try {
fRead = new FileReader("in.txt");
BufferedReader reader = new BufferedReader(fRead);
fileIn = reader.readLine();
bFile = fileIn.getBytes("UTF-8");
fWrite = new FileWriter("out.txt");
BufferedWriter writer = new BufferedWriter(fWrite);
for (byte b: bFile) {
writer.write(binaryString(b));
System.out.println(binaryString(b));
}
System.out.println("Done.");
} catch (Exception e) {
e.printStackTrace();
}
}
public Binary() {
}
public static void main(String[] args) throws UnsupportedEncodingException, IOException {
Binary b = new Binary();
b.input();
}
}
我知道我的代码不是很好,我对Java来说还比较陌生,所以我不知道其他许多方法可以实现这一目标.
I know my code is not very good, I'm relatively new to Java so I don't know many others ways to accomplish this.
推荐答案
使用输出流而不是Writer,因为不应该使用writer来编写二进制内容
Use Output stream instead of Writer as writer is not supposed to be used for writing binary content
FileOutputStream fos = new FileOutputStream(new File("output.txt"));
BufferedOutputStream bos = new BufferedOutputStream(fos);
bos.write(b); // in loop probably
这篇关于如何用Java将二进制文件写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!