首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Java中巧妙地将文件读入byte[]数组

在Java中巧妙地将文件读入byte[]数组
EN

Stack Overflow用户
提问于 2011-05-19 19:35:26
回答 6查看 172K关注 0票数 75

可能重复:

File to byte[] in Java

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

代码语言:javascript
复制
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[]中?:)

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2011-05-19 19:41:09

很久以前:

调用其中的任何一个

代码语言:javascript
复制
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 API级别的26+)

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

代码语言:javascript
复制
byte[] java.nio.file.Files.readAllBytes(Path path)

Javadoc here

票数 143
EN

Stack Overflow用户

发布于 2011-09-29 08:38:45

这也是可行的:

代码语言:javascript
复制
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();
        }
    }
}
票数 65
EN

Stack Overflow用户

发布于 2011-05-19 19:42:12

如果使用Google Guava (如果不使用,则应该使用),可以调用:ByteStreams.toByteArray(InputStream)Files.toByteArray(File)

票数 40
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6058003

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档