可能是重复问题:
Java中将文件转换为byte[]数组
我想从文件中读取数据并将其解组到Parcel中。 在文档中,对于FileInputStream的read方法不明确,无法读取所有内容。为了实现这一点,我进行如下操作:
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[]? :)
IOUtils.toByteArray(InputStream)
也可以使用,不过FileUtils
的方法应该更有效率。 - Stephen Cjava.io.InputStream
API来完成此操作... - Lukas Eder