可能重复:
File to byte[] in Java
我想从文件中读取数据并将其解组为Parcel。 在文档中不清楚,FileInputStream具有读取其所有内容的方法。为了实现这一点,我做了以下事情:
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 []中? :)
答案 0 :(得分:135)
调用其中任何一个
byte[] org.apache.commons.io.FileUtils.readFileToByteArray(File file)
byte[] org.apache.commons.io.IOUtils.toByteArray(InputStream input)
这
如果您的Android应用程序的库占用空间太大,您可以使用commons-io库中的相关类
幸运的是,我们现在在nio包中有一些便利方法。例如:
byte[] java.nio.file.Files.readAllBytes(Path path)
答案 1 :(得分:60)
这也有效:
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();
}
}
}
答案 2 :(得分:37)
如果您使用Google Guava(如果不这样做,则应该),您可以致电:ByteStreams.toByteArray(InputStream)
或Files.toByteArray(File)
答案 3 :(得分:17)
这对我有用:
File file = ...;
byte[] data = new byte[(int) file.length()];
try {
new FileInputStream(file).read(data);
} catch (Exception e) {
e.printStackTrace();
}
答案 4 :(得分:13)
使用ByteArrayOutputStream
。这是过程:
InputStream
来读取数据ByteArrayOutputStream
。InputStream
复制到OutputStream
toByteArray()
方法byte[]
获取ByteArrayOutputStream
答案 5 :(得分:7)
看看下面的apache commons函数:
org.apache.commons.io.FileUtils.readFileToByteArray(File)