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


当前回答

正如有人所说,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);
        ...
    }
}

其他回答

如果你的目标版本少于26个API,试试这个

 private static byte[] readFileToBytes(String filePath) {

    File file = new File(filePath);
    byte[] bytes = new byte[(int) file.length()];

    // funny, if can use Java 7, please uses Files.readAllBytes(path)
    try(FileInputStream fis = new FileInputStream(file)){
        fis.read(bytes);
        return bytes;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;

}

这取决于什么对你来说是最好的。就生产力而言,不要重复工作,而是使用Apache Commons。FileUtils。readFileToByteArray(文件输入)。

如果你没有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();
}

调用者负责关闭流。

正如有人所说,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);
        ...
    }
}

让我添加另一个不使用第三方库的解决方案。它重用了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;
}