Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何用Java将二进制文件写入文件_Java_File Io_Binary - Fatal编程技术网

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

如何用Java将二进制文件写入文件,java,file-io,binary,Java,File Io,Binary,我试图从文件中获取输入,将字符转换为二进制,然后将二进制输出到另一个输出文件 我使用Integer.tobinarysting进行转换 一切都正常工作,但由于某些原因,没有写入输出文件,但当我使用System.out.println时,输出很好 import java.io.*; public class Binary { FileReader fRead = null; FileWriter fWrite = null; byte[] bFile = null;

我试图从文件中获取输入,将字符转换为二进制,然后将二进制输出到另一个输出文件

我使用Integer.tobinarysting进行转换

一切都正常工作,但由于某些原因,没有写入输出文件,但当我使用System.out.println时,输出很好

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比较陌生,所以我不知道其他很多方法来实现这一点。

使用输出流而不是编写器,因为编写器不应该用于编写二进制内容

FileOutputStream fos = new FileOutputStream(new File("output.txt"));
BufferedOutputStream bos = new BufferedOutputStream(fos);
bos.write(b); // in loop probably

请记住关闭您打开的每个文件。我收到一个错误,因为binaryString返回字符串值,而BufferedOutputStream无法写入字符串。由于我无法将返回类型更改为int,因此解决方法是什么。没关系,我将其更改为bos.writeb;并将其写入output.txt。非常感谢。