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

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

问题描述

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

我想从文件中读取数据并将其解组到 Parcel.在文档中不清楚 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);

我觉得这段代码很难看,我的问题是:如何从文件中读取数据到 byte[] 中?:)

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

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

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