如何从文件中读取字节,而结果byte []完全一样长

Dan*_*ode 2 java file-io

我希望结果byte[]与文件内容完全一样长.如何实现这一目标.

我在考虑ArrayList<Byte>,但它似乎没有效率.

Joa*_*uer 5

我个人会去番石榴路线:

File f = ...
byte[] content = Files.toByteArray(f);
Run Code Online (Sandbox Code Playgroud)

如果需要,Apache Commons IO具有类似的实用方法.

如果这不是您想要的,那么自己编写代码并不难:

public static byte[] toByteArray(File f) throws IOException {
    if (f.length() > Integer.MAX_VALUE) {
        throw new IllegalArgumentException(f + " is too large!");
    }
    int length = (int) f.length();
    byte[] content = new byte[length];
    int off = 0;
    int read = 0;
    InputStream in = new FileInputStream(f);
    try {
        while (read != -1 && off < length) {
            read = in.read(content, off, (length - off));
            off += read;
        }
        if (off != length) {
            // file size has shrunken since check, handle appropriately
        } else if (in.read() != -1) {
            // file size has grown since check, handle appropriately
        }
        return content;
    } finally {
        in.close();
    }
}
Run Code Online (Sandbox Code Playgroud)