Java中将文件读入byte[]数组的优雅方法

发布于 2024-11-08 13:38:43 字数 1310 浏览 0 评论 0原文

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

我想从文件中读取数据并将其解组到包裹。 在文档中尚不清楚 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[]中? :)

Possible Duplicate:
File to byte[] in Java

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? :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

蒗幽 2024-11-15 13:38:43

很久以前:

调用其中任何一个

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 包中提供了一些方便的方法。例如:

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

这里是 Javadoc

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) 

From

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

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

Today (Java 7+ or Android API Level 26+)

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

说不完的你爱 2024-11-15 13:38:43

这也将起作用:

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

This will also work:

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();
        }
    }
}
べ映画 2024-11-15 13:38:43

如果您使用 Google Guava(如果没有,您应该使用),您可以调用:< a href="http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/io/ByteStreams.html#toByteArray(java.io.InputStream)" rel="noreferrer">< code>ByteStreams.toByteArray(InputStream) 或 Files.toByteArray(File)

If you use Google Guava (and if you don't, you should), you can call: ByteStreams.toByteArray(InputStream) or Files.toByteArray(File)

赤濁 2024-11-15 13:38:43

这对我有用:

File file = ...;
byte[] data = new byte[(int) file.length()];
try {
    new FileInputStream(file).read(data);
} catch (Exception e) {
    e.printStackTrace();
}

This works for me:

File file = ...;
byte[] data = new byte[(int) file.length()];
try {
    new FileInputStream(file).read(data);
} catch (Exception e) {
    e.printStackTrace();
}
你的笑 2024-11-15 13:38:43

使用 ByteArrayOutputStream。流程如下:

  • 获取一个InputStream来读取数据
  • 创建一个ByteArrayOutputStream
  • 将所有 InputStream 复制到 OutputStream
  • 使用 toByteArray() 方法

Use a ByteArrayOutputStream. Here is the process:

  • Get an InputStream to read data
  • Create a ByteArrayOutputStream.
  • Copy all the InputStream into the OutputStream
  • Get your byte[] from the ByteArrayOutputStream using the toByteArray() method
葬心 2024-11-15 13:38:43

看看下面的 apache commons 函数:

org.apache.commons.io.FileUtils.readFileToByteArray(File)

Have a look at the following apache commons function:

org.apache.commons.io.FileUtils.readFileToByteArray(File)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文