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


当前回答

import java.io.RandomAccessFile;
RandomAccessFile f = new RandomAccessFile(fileName, "r");
byte[] b = new byte[(int)f.length()];
f.readFully(b);

Java 8文档:http://docs.oracle.com/javase/8/docs/api/java/io/RandomAccessFile.html

其他回答

让我添加另一个不使用第三方库的解决方案。它重用了Scott提出的异常处理模式(链接)。我把丑陋的部分移动到一个单独的消息(我会隐藏在一些FileUtils类;))

public void someMethod() {
    final byte[] buffer = read(new File("test.txt"));
}

private byte[] read(final File file) {
    if (file.isDirectory())
        throw new RuntimeException("Unsupported operation, file "
                + file.getAbsolutePath() + " is a directory");
    if (file.length() > Integer.MAX_VALUE)
        throw new RuntimeException("Unsupported operation, file "
                + file.getAbsolutePath() + " is too big");

    Throwable pending = null;
    FileInputStream in = null;
    final byte buffer[] = new byte[(int) file.length()];
    try {
        in = new FileInputStream(file);
        in.read(buffer);
    } catch (Exception e) {
        pending = new RuntimeException("Exception occured on reading file "
                + file.getAbsolutePath(), e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (Exception e) {
                if (pending == null) {
                    pending = new RuntimeException(
                        "Exception occured on closing file" 
                             + file.getAbsolutePath(), e);
                }
            }
        }
        if (pending != null) {
            throw new RuntimeException(pending);
        }
    }
    return buffer;
}
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);
        }
    }
}

ReadFully从当前文件指针开始,将b.length字节从这个文件读入字节数组。该方法从文件中重复读取,直到读取所请求的字节数。该方法将阻塞,直到读取请求的字节数、检测到流的末尾或抛出异常。

RandomAccessFile f = new RandomAccessFile(fileName, "r");
byte[] b = new byte[(int)f.length()];
f.readFully(b);

如果您想将字节读入预分配的字节缓冲区,这个答案可能会有所帮助。

您的第一个猜测可能是使用InputStream read(byte[])。然而,这种方法有一个缺陷,使得它难以使用:即使没有遇到EOF,也不能保证数组实际上会被完全填充。

相反,看一下DataInputStream readFully(byte[])。这是一个输入流的包装器,没有上面提到的问题。此外,该方法在遇到EOF时抛出。好得多。

试试这个:

import sun.misc.IOUtils;
import java.io.IOException;

try {
    String path="";
    InputStream inputStream=new FileInputStream(path);
    byte[] data=IOUtils.readFully(inputStream,-1,false);
}
catch (IOException e) {
    System.out.println(e);
}