简体   繁体   English

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

[英]how can i read from a binary file?

I want to read a binary file that its size is 5.5 megabyte (a mp3 file).我想读取一个大小为5.5 megabyte的二进制文件(一个 mp3 文件)。 I tried it with fileinputstream but it took many attempts.我用fileinputstream尝试过,但尝试了很多次。 If possible, I want to read file with a minimal waste of time.如果可能的话,我想以最少的时间浪费来读取文件。

You should try to use a BufferedInputStream around your FileInputStream.您应该尝试在 FileInputStream 周围使用 BufferedInputStream。 It will improve the performance significantly.它将显着提高性能。

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

Furthermore, I'd recommend to use the read-method that takes a byte array and fills it instead of the plain read.此外,我建议使用读取字节数组并填充它而不是普通读取的读取方法。

There are useful utilities in FileUtils for reading a file at once. FileUtils中有用于一次读取文件的有用实用程序。 This is simpler and efficient for modest files up to 100 MB.对于最大 100 MB 的普通文件,这更简单有效。

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

Try this:尝试这个:

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

A more reliable version based on helpful comment from @Paul Cager & Liv related to available 's and read 's unreliability.一个更可靠的版本,基于来自 @Paul Cager & Liv 的有用评论,与availableread的不可靠性有关。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM