在Java中将文件读入byte 数组的优雅方式

可能重复:
文件到Java中的byte []

我想从文件中读取数据并将其解组到Parcel。 在文档中并不清楚,FileInputStream有读取其所有内容的方法。 为了实现这一点,我做了如下:

FileInputStream filein = context.openFileInput(FILENAME); int read = 0; int offset = 0; int chunk_size = 1024; int total_size = 0; ArrayList<byte[]> chunks = new ArrayList<byte[]>(); chunks.add(new byte[chunk_size]); //first I read data from file chunk by chunk while ( (read = filein.read(chunks.get(chunks.size()-1), offset, buffer_size)) != -1) { total_size+=read; if (read == buffer_size) { chunks.add(new byte[buffer_size]); } } int index = 0; // then I create big buffer byte[] rawdata = new byte[total_size]; // then I copy data from every chunk in this buffer for (byte [] chunk: chunks) { for (byte bt : chunk) { index += 0; rawdata[index] = bt; if (index >= total_size) break; } if (index>= total_size) break; } // and clear chunks array chunks.clear(); // finally I can unmarshall this data to Parcel Parcel parcel = Parcel.obtain(); parcel.unmarshall(rawdata,0,rawdata.length); 

我认为这个代码看起来很丑,我的问题是:如何从文件读取数据精确到byte []? 🙂

很久以前:

打电话任何这些

 byte[] org.apache.commons.io.FileUtils.readFileToByteArray(File file) byte[] org.apache.commons.io.IOUtils.toByteArray(InputStream input) 

http://commons.apache.org/io/

如果库的占用空间对于Android应用程序来说太大,则可以使用commons-io库中的相关类

今天(Java 7+,如果你不使用Android)

幸运的是,我们现在在nio软件包中有一些方便的方法。 例如:

 byte[] java.nio.file.Files.readAllBytes(Path path) 

Javadoc在这里

这也将工作:

 import java.io.*; public class IOUtil { public static byte[] readFile(String file) throws IOException { return readFile(new File(file)); } public static byte[] readFile(File file) throws IOException { // Open file RandomAccessFile f = new RandomAccessFile(file, "r"); try { // Get and check length long longlength = f.length(); int length = (int) longlength; if (length != longlength) throw new IOException("File size >= 2 GB"); // Read file and return data byte[] data = new byte[length]; f.readFully(data); return data; } finally { f.close(); } } } 

如果你使用谷歌番石榴 (如果你不这样做,你应该),你可以调用: Files.toByteArray(File) ByteStreams.toByteArray(InputStream)Files.toByteArray(File)

这适用于我:

 File file = ...; byte[] data = new byte[(int) file.length()]; try { new FileInputStream(file).read(data); } catch (Exception e) { e.printStackTrace(); } 

使用ByteArrayOutputStream 。 过程如下:

  • 获取一个InputStream来读取数据
  • 创build一个ByteArrayOutputStream
  • 将所有的InputStream复制到OutputStream
  • 使用toByteArray()方法从ByteArrayOutputStream获取byte[]

看看下面的apache commonsfunction:

 org.apache.commons.io.FileUtils.readFileToByteArray(File)