I am trying to get input from a file, convert the characters to binary and then output the binary to another output file.
I used Integer.toBinaryString() in order to make the conversion.
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();
}
}
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.
解决方案
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