我如何从二进制文件中读取?

时间:2011-06-08 10:45:05

标签: java file

我想读一个大小为5.5 megabyte的二进制文件(一个mp3文件)。我用fileinputstream尝试了它,但它花了很多次尝试。如果可能的话,我想以最少的浪费时间阅读文件。

3 个答案:

答案 0 :(得分:4)

您应该尝试在FileInputStream周围使用BufferedInputStream。它将显着提高性能。

new BufferedInputStream(fileInputStream, 8192 /* default buffer size */);

此外,我建议使用读取方法,该方法接受一个字节数组并填充它而不是普通读取。

答案 1 :(得分:2)

FileUtils中有一些有用的实用程序可以立即读取文件。对于最大100 MB的适度文件,这更简单有效。

byte[] bytes = FileUtils.readFileToByteArray(file); // handles IOException/close() etc.

答案 2 :(得分:-1)

试试这个:

public static void main(String[] args) throws IOException
{
    InputStream i = new FileInputStream("a.mp3");
    byte[] contents = new byte[i.available()];
    i.read(contents);
    i.close();
}

更可靠的版本基于来自@Paul Cager&的有用评论Liv与可用读取的不可靠性有关。

public static void main(String[] args) throws IOException
{
    File f = new File("c:\\msdia80.dll");
    InputStream i = new FileInputStream(f);
    byte[] contents = new byte[(int) f.length()];

    int read;
    int pos = 0;
    while ((read = i.read(contents, pos, contents.length - pos)) >= 1)
    {
        pos += read;
    }
    i.close();
}