文件到Java中的byte

如何将java.io.File转换为byte[]

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

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

例:

 import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.Path; Path path = Paths.get("path/to/file"); byte[] data = Files.readAllBytes(path); 
 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

由于JDK 7 – 内胆:

 byte[] array = Files.readAllBytes(new File("/path/to/file").toPath()); 

不需要外部依赖。

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

最简单的方法是这样的:

 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(); } 

这有一些不必要的文件内容复制(实际上数据被复制三次:从文件到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; } 

这没有不必要的复制。

FileTooBigException是一个自定义应用程序exception。 MAX_FILE_SIZE常量是一个应用程序参数。

对于大文件,您应该考虑使用stream处理algorithm或使用内存映射(请参见java.nio )。

正如有人所说, 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 { String fileName = ... byte[] data = FileUtils.readFileToByteArray(fileName); ... } } 

您也可以使用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(); } } 

我认为它使用MappedByteBuffer以来速度非常快。

 // 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; } 

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

来电者负责closuresstream。

番石榴有Files.toByteArray()为您提供。 它有几个优点:

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

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

 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); } } } 

简单的方法来做到这一点:

  File fff = new File("/path/to/file"); FileInputStream fileInputStream = new FileInputStream(fff); int byteLength=fff.length(); //bytecount of the file-content byte[] filecontent = new byte[byteLength]; fileInputStream.read(filecontent,0,byteLength); 

使用与社区维基答案相同的方法,但更清洁并编译出来(如果您不想导入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(); } 
 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); 

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

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

ReadFully从此文件读取b.length个字节到当前文件指针开始的字节数组中。 该方法从文件中重复读取,直到读取所请求的字节数。 此方法将阻塞,直到读取所请求的字节数,检测到stream的结尾,或抛出exception。

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

让我添加另一个解决scheme,而不使用第三方库。 它重新使用Scott提出的exception处理模式( 链接 )。 我把这个丑陋的部分移到了一个单独的消息中(我会隐藏在一些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; } 

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

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

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

 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); } } } 

从文件读取字节的另一种方法

 Reader reader = null; try { reader = new FileReader(file); char buf[] = new char[8192]; int len; StringBuilder s = new StringBuilder(); while ((len = reader.read(buf)) >= 0) { s.append(buf, 0, len); byte[] byteArray = s.toString().getBytes(); } } catch(FileNotFoundException ex) { } catch(IOException e) { } finally { if (reader != null) { reader.close(); } }