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


当前回答

Guava有Files.toByteArray()可以提供给您。它有几个优点:

它涵盖了文件报告长度为0但仍然有内容的极端情况 它是高度优化的,如果在加载文件之前试图读入一个大文件,你会得到一个OutOfMemoryException。(通过巧妙地使用file.length()) 你没必要白费力气。

其他回答

public static byte[] readBytes(InputStream inputStream) throws IOException {
    byte[] buffer = new byte[32 * 1024];
    int bufferSize = 0;
    for (;;) {
        int read = inputStream.read(buffer, bufferSize, buffer.length - bufferSize);
        if (read == -1) {
            return Arrays.copyOf(buffer, bufferSize);
        }
        bufferSize += read;
        if (bufferSize == buffer.length) {
            buffer = Arrays.copyOf(buffer, bufferSize * 2);
        }
    }
}

正如有人所说,Apache Commons File Utils可能有您正在寻找的东西

public static byte[] readFileToByteArray(File file) throws IOException

示例使用(Program.java):

import org.apache.commons.io.FileUtils;
public class Program {
    public static void main(String[] args) throws IOException {
        File file = new File(args[0]);  // assume args[0] is the path to file
        byte[] data = FileUtils.readFileToByteArray(file);
        ...
    }
}

Guava有Files.toByteArray()可以提供给您。它有几个优点:

它涵盖了文件报告长度为0但仍然有内容的极端情况 它是高度优化的,如果在加载文件之前试图读入一个大文件,你会得到一个OutOfMemoryException。(通过巧妙地使用file.length()) 你没必要白费力气。

你也可以使用NIO api来实现。只要总文件大小(以字节为单位)适合int类型,我就可以用这段代码做到这一点。

File f = new File("c:\\wscp.script");
FileInputStream fin = null;
FileChannel ch = null;
try {
    fin = new FileInputStream(f);
    ch = fin.getChannel();
    int size = (int) ch.size();
    MappedByteBuffer buf = ch.map(MapMode.READ_ONLY, 0, size);
    byte[] bytes = new byte[size];
    buf.get(bytes);

} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} finally {
    try {
        if (fin != null) {
            fin.close();
        }
        if (ch != null) {
            ch.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

我认为它非常快,因为它使用MappedByteBuffer。

如果你没有Java 8,并且同意我的观点,加入一个庞大的库来避免写几行代码是一个坏主意:

public static byte[] readBytes(InputStream inputStream) throws IOException {
    byte[] b = new byte[1024];
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    int c;
    while ((c = inputStream.read(b)) != -1) {
        os.write(b, 0, c);
    }
    return os.toByteArray();
}

调用者负责关闭流。