在Java中将文件转换为byte []

Ben*_*and 711 java file-io

如何将a转换java.io.Filebyte[]

小智 1228

JDK 7开始,您可以使用Files.readAllBytes(Path).

例:

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

File file;
// ...(file is initialised)...
byte[] fileContent = Files.readAllBytes(file.toPath());
Run Code Online (Sandbox Code Playgroud)

  • @ aldo.roman.nurena JDK7引入了一个File.toPath()方法,它将为您提供一个Path对象. (77认同)
  • 我有一个File对象,而不是一个路径(来自http post请求) (8认同)
  • 您可以从文件中获取路径.尝试:文件文件=新文件("/ path"); 路径路径= Paths.get(file.getAbsolutePath()); byte [] data = Files.readAllBytes(path); (6认同)
  • @akauppi请参阅答案中的链接:"该方法确保文件已关闭......" (4认同)
  • 如何在java.nio中处理文件关闭 - 换句话说,如果上面的代码关闭了什么? (2认同)
  • 现在,如果针对SDK版本26及更高版本,这适用于Android. (2认同)

sva*_*hon 462

这取决于你最好的方法.生产力明智,不要重新发明轮子并使用Apache Commons.这是在这里IOUtils.toByteArray(InputStream input).

  • @ymajoros:真的!我宁愿有一些额外的代码行而不是另一个依赖.依赖性隐藏了成本.您需要了解该库的最新信息,在构建脚本中包含依赖项等,使用您的代码等将其传达给人们.如果您已经使用了具有代码的库而不是使用它,那么我会说自己写吧. (25认同)
  • 这回答了如何读取文件的问题,而不是如何将java.IO.File类型的对象转换为byte []的问题. (8认同)
  • 这怎么用来读`````byte []`?我正在使用Java6所以我不能使用NIO方法:( (5认同)
  • @ymajoros你愿意与我们分享任何"标准3线解决方案",所以我们不必依靠重新发明轮子依赖吗? (4认同)
  • @matteo:没有?请参阅其他答案,例如Files.readAllBytes().简单,没有依赖. (2认同)
  • **注意** API 文档中有关 `Files.readAllBytes()` 的引用:“请注意,此方法适用于可以方便地将所有字节读入字节数组的简单情况。它不适用于读入大文件。” (2认同)

Pau*_*nis 183

从JDK 7开始 - 一个班轮:

byte[] array = Files.readAllBytes(Paths.get("/path/to/file"));
Run Code Online (Sandbox Code Playgroud)

不需要外部依赖.

  • 现在这是一个比接受的答案更好的选择,这需要Apache Commons. (11认同)
  • 在Android中,它需要min API级别为26. (4认同)
  • 如果尚未添加,则需要添加“import java.nio.file.Files;”和“import java.nio.file.Paths;”。 (3认同)

Dmi*_*ich 161

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

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

  • 只有在您正在阅读文件时,才会出现这种情况.在所有其他情况下抛出IOException.为了解决这个问题,我建议以读写模式打开文件:RandomAccessFile(fileName,"rw") (8认同)
  • 我可以想象只读取文件的一部分的其他来源(文件在网络共享...)readFully()有您正在搜索的合同. (5认同)
  • 请记住,RandomAccessFile不是线程安全的.因此,在某些情况下可能需要同步. (3认同)
  • 你必须检查f.read()的返回值.有时会发生这种情况,你不会读取整个文件. (2认同)

Mih*_*der 76

基本上你必须在内存中阅读它.打开文件,分配数组,并将文件中的内容读入数组.

最简单的方法是这样的:

public byte[] read(File file) throws IOException, FileTooBigException {
    if (file.length() > MAX_FILE_SIZE) {
        throw new FileTooBigException(file);
    }
    ByteArrayOutputStream ous = null;
    InputStream ios = null;
    try {
        byte[] buffer = new byte[4096];
        ous = new ByteArrayOutputStream();
        ios = new FileInputStream(file);
        int read = 0;
        while ((read = ios.read(buffer)) != -1) {
            ous.write(buffer, 0, read);
        }
    }finally {
        try {
            if (ous != null)
                ous.close();
        } catch (IOException e) {
        }

        try {
            if (ios != null)
                ios.close();
        } catch (IOException e) {
        }
    }
    return ous.toByteArray();
}
Run Code Online (Sandbox Code Playgroud)

这具有这样的文件内容的一些不必要的复制(实际上数据被复制三次:从文件buffer,从bufferByteArrayOutputStream,从ByteArrayOutputStream实际得到的数组).

您还需要确保在内存中只读取一定大小的文件(这通常取决于应用程序):-).

你还需要对待IOException外部的功能.

另一种方式是这样的:

public byte[] read(File file) throws IOException, FileTooBigException {
    if (file.length() > MAX_FILE_SIZE) {
        throw new FileTooBigException(file);
    }

    byte[] buffer = new byte[(int) file.length()];
    InputStream ios = null;
    try {
        ios = new FileInputStream(file);
        if (ios.read(buffer) == -1) {
            throw new IOException(
                    "EOF reached while trying to read the whole file");
        }
    } finally {
        try {
            if (ios != null)
                ios.close();
        } catch (IOException e) {
        }
    }
    return buffer;
}
Run Code Online (Sandbox Code Playgroud)

这没有不必要的复制.

FileTooBigException是自定义应用程序例外.该MAX_FILE_SIZE常数是一个应用程序的参数.

对于大文件,您应该考虑使用流处理算法或使用内存映射(请参阅参考资料java.nio).


Tom*_*Tom 72

正如有人所说,Apache Commons File Utils可能有你想要的东西

public static byte[] readFileToByteArray(File file) throws IOException
Run Code Online (Sandbox Code Playgroud)

示例use(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);
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)


Ami*_*mit 22

您也可以使用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();
    }
}
Run Code Online (Sandbox Code Playgroud)

我认为它使用MappedByteBuffer非常快.

  • 如果你只想读取一次文件,那么绝对不需要使用内存映射,它最终会使用比使用普通FileInputStream多两倍的内存. (2认同)
  • 真棒,新的例子包括printStackTrace,经典的破坏异常处理. (2认同)

Jef*_*man 20

如果您没有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();
}
Run Code Online (Sandbox Code Playgroud)

呼叫者负责关闭流.


Cug*_*uga 19

// Returns the contents of the file in a byte array.
    public static byte[] getBytesFromFile(File file) throws IOException {        
        // Get the size of the file
        long length = file.length();

        // You cannot create an array using a long type.
        // It needs to be an int type.
        // Before converting to an int type, check
        // to ensure that file is not larger than Integer.MAX_VALUE.
        if (length > Integer.MAX_VALUE) {
            // File is too large
            throw new IOException("File is too large!");
        }

        // Create the byte array to hold the data
        byte[] bytes = new byte[(int)length];

        // Read in the bytes
        int offset = 0;
        int numRead = 0;

        InputStream is = new FileInputStream(file);
        try {
            while (offset < bytes.length
                   && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
                offset += numRead;
            }
        } finally {
            is.close();
        }

        // Ensure all the bytes have been read in
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file "+file.getName());
        }
        return bytes;
    }
Run Code Online (Sandbox Code Playgroud)


Sud*_*ari 17

简单的方法:

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);
Run Code Online (Sandbox Code Playgroud)


Sac*_*mar 17

这是最简单的方法之一

 String pathFile = "/path/to/file";
 byte[] bytes = Files.readAllBytes(Paths.get(pathFile ));
Run Code Online (Sandbox Code Playgroud)


小智 14

从文件中读取字节的最简单方法

import java.io.*;

class ReadBytesFromFile {
    public static void main(String args[]) throws Exception {
        // getBytes from anyWhere
        // I'm getting byte array from File
        File file = null;
        FileInputStream fileStream = new FileInputStream(file = new File("ByteArrayInputStreamClass.java"));

        // Instantiate array
        byte[] arr = new byte[(int) file.length()];

        // read All bytes of File stream
        fileStream.read(arr, 0, arr.length);

        for (int X : arr) {
            System.out.print((char) X);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 没什么特别的,但是您说的是最简单的,而且我看到了更多简单的解决方案-&gt;我认为这不是最简单的。也许是几年前,但是世界正在改变。我不会用这样的声明来标记自己的解决方案。;)如果只写了“在我看来,最简单的就是..”或“我发现的最简单的..”。您不想打扰您,只是想好好传达一下。 (3认同)

jon*_*ejj 11

Guava有Files.toByteArray()为您提供.它有几个优点:

  1. 它涵盖了文件报告长度为0但仍有内容的角落情况
  2. 它是高度优化的,如果在尝试加载文件之前尝试读取大文件,则会出现OutOfMemoryException.(通过巧妙地使用file.length())
  3. 你不必重新发明轮子.


Blo*_*ode 11

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

File file = getYourFile();
Path path = file.toPath();
byte[] data = Files.readAllBytes(path);
Run Code Online (Sandbox Code Playgroud)


man*_*mal 10

使用与社区维基答案相同的方法,但更清晰和开箱即用的编译(如果您不想导入Apache Commons库,首选方法,例如在Android上):

public static byte[] getFileBytes(File file) throws IOException {
    ByteArrayOutputStream ous = null;
    InputStream ios = null;
    try {
        byte[] buffer = new byte[4096];
        ous = new ByteArrayOutputStream();
        ios = new FileInputStream(file);
        int read = 0;
        while ((read = ios.read(buffer)) != -1)
            ous.write(buffer, 0, read);
    } finally {
        try {
            if (ous != null)
                ous.close();
        } catch (IOException e) {
            // swallow, since not that important
        }
        try {
            if (ios != null)
                ios.close();
        } catch (IOException e) {
            // swallow, since not that important
        }
    }
    return ous.toByteArray();
}
Run Code Online (Sandbox Code Playgroud)


小智 7

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

org.apache.commons.io.FileUtils.readFileToByteArray(file);
Run Code Online (Sandbox Code Playgroud)

  • 汤姆在2009年的这个建议已经有了答案 (7认同)

Lau*_*lst 5

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

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

相反,看看DataInputStream readFully(byte[]). 这是输入流的包装器,没有上述问题。此外,此方法在遇到 EOF 时抛出。好多了。


小智 5

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

RandomAccessFile f = new RandomAccessFile(fileName, "r");
byte[] b = new byte[(int)f.length()];
f.readFully(b);
Run Code Online (Sandbox Code Playgroud)


gom*_*sha 5

以下方法不仅将 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);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)


小智 5

//The file that you wanna convert into byte[]
File file=new File("/storage/0CE2-EA3D/DCIM/Camera/VID_20190822_205931.mp4"); 

FileInputStream fileInputStream=new FileInputStream(file);
byte[] data=new byte[(int) file.length()];
BufferedInputStream bufferedInputStream=new BufferedInputStream(fileInputStream);
bufferedInputStream.read(data,0,data.length);

//Now the bytes of the file are contain in the "byte[] data"
Run Code Online (Sandbox Code Playgroud)