我如何将java.io.File转换为字节[]?


当前回答

我相信这是最简单的方法:

org.apache.commons.io.FileUtils.readFileToByteArray(file);

其他回答

从文件中读取字节的另一种方法

Reader reader = null;
    try {
        reader = new FileReader(file);
        char buf[] = new char[8192];
        int len;
        StringBuilder s = new StringBuilder();
        while ((len = reader.read(buf)) >= 0) {
            s.append(buf, 0, len);
            byte[] byteArray = s.toString().getBytes();
        }
    } catch(FileNotFoundException ex) {
    } catch(IOException e) {
    }
    finally {
        if (reader != null) {
            reader.close();
        }
    }

可以像这样简单地完成(Kotlin版本)

val byteArray = File(path).inputStream().readBytes()

编辑:

我读过readBytes方法的文档。它说:

将此流完全读入字节数组。 注意:关闭这个流是调用者的责任。

因此,为了能够关闭流,同时保持一切干净,使用以下代码:

val byteArray = File(path).inputStream().use { it.readBytes() }

感谢@user2768856指出这一点。

从JDK 7开始,您可以使用Files.readAllBytes(Path)。

例子:

import java.io.File;
import java.nio.file.Files;

File file;
// ...(file is initialised)...
byte[] fileContent = Files.readAllBytes(file.toPath());

从文件中读取字节的最简单方法

import java.io.*;

class ReadBytesFromFile {
    public static void main(String args[]) throws Exception {
        // getBytes from anyWhere
        // I'm getting byte array from File
        File file = null;
        FileInputStream fileStream = new FileInputStream(file = new File("ByteArrayInputStreamClass.java"));

        // Instantiate array
        byte[] arr = new byte[(int) file.length()];

        // read All bytes of File stream
        fileStream.read(arr, 0, arr.length);

        for (int X : arr) {
            System.out.print((char) X);
        }
    }
}

在JDK8

Stream<String> lines = Files.lines(path);
String data = lines.collect(Collectors.joining("\n"));
lines.close();