在Java中将文件读入byte []数组的优雅方式 [英] Elegant way to read file into byte[] array in Java

查看:138
本文介绍了在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);

我认为这段代码看起来很丑陋,我的问题是:
如何读取数据从文件到字节[]精美? :

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

推荐答案

很久以前:



这些

A long time ago:

Call any of these

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库中的相关课程

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)

Javadoc here

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

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