优雅的方式来读取文件到字节[]在Java数组 [英] Elegant way to read file into byte[] array in Java

查看:187
本文介绍了优雅的方式来读取文件到字节[]在Java数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
  文件为byte []在Java中

我想从文件中读取数据,并将其解组到地块。 在文档目前尚不清楚,那的FileInputStream有方法来读取它的所有内容。要实现这一点,我做如下因素:

I want to read data from file and unmarshal it to Parcel. In documentation it is not clear, that FileInputStream has method to read all its content. To implement this, I do folowing:

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

我觉得这$​​ C $ C长相丑陋,我的问题是: 如何从文件中做数据读入byte []的美丽? :)

I think this code looks ugly, and my question is: How to do read data from file into byte[] beautifully? :)

推荐答案

调用任何这些

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

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

如果库占用太大的Andr​​oid应用程序,你可以使用相关的类从公地IO库

If the library footprint is too big for your Android app, you can just use relevant classes from the commons-io library

幸运的是,我们现在有几个在NIO包方便的方法。例如:

Luckily, we now have a couple of convenience methods in the nio packages. For instance:

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

<一个href="http://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#readAllBytes-java.nio.file.Path-">Javadoc这里

这篇关于优雅的方式来读取文件到字节[]在Java数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆