java二进制文件读写文件,如何用Java将二进制文件写入文件

该博客探讨了使用Java进行文件操作,从读取文本文件到将字符转换为二进制,然后将二进制数据写入另一个输出文件的过程。作者使用Integer.toBinaryString()方法进行转换,但遇到问题:二进制数据未成功写入输出文件,尽管在控制台打印正常。解决方案建议使用OutputStream代替Writer,因为Writer不适用于二进制内容的写入。
摘要由CSDN通过智能技术生成

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值