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


当前回答

以下方法不仅将Java .io. file转换为byte[],我还发现它是读取文件的最快方法,当测试许多不同的Java文件读取方法时:

java.nio.file.Files.readAllBytes ()

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

public class ReadFile_Files_ReadAllBytes {
  public static void main(String [] pArgs) throws IOException {
    String fileName = "c:\\temp\\sample-10KB.txt";
    File file = new File(fileName);

    byte [] fileBytes = Files.readAllBytes(file.toPath());
    char singleChar;
    for(byte b : fileBytes) {
      singleChar = (char) b;
      System.out.print(singleChar);
    }
  }
}

其他回答

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

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

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

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

简单的方法:

File fff = new File("/path/to/file");
FileInputStream fileInputStream = new FileInputStream(fff);

// int byteLength = fff.length(); 

// In android the result of file.length() is long
long byteLength = fff.length(); // byte count of the file-content

byte[] filecontent = new byte[(int) byteLength];
fileInputStream.read(filecontent, 0, (int) byteLength);

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

以下方法不仅将Java .io. file转换为byte[],我还发现它是读取文件的最快方法,当测试许多不同的Java文件读取方法时:

java.nio.file.Files.readAllBytes ()

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

public class ReadFile_Files_ReadAllBytes {
  public static void main(String [] pArgs) throws IOException {
    String fileName = "c:\\temp\\sample-10KB.txt";
    File file = new File(fileName);

    byte [] fileBytes = Files.readAllBytes(file.toPath());
    char singleChar;
    for(byte b : fileBytes) {
      singleChar = (char) b;
      System.out.print(singleChar);
    }
  }
}