how can i read from a binary file?

99封情书 提交于 2021-02-17 06:09:38

问题


I want to read a binary file that its size is 5.5 megabyte(a mp3 file). I tried it with fileinputstream but it took many attempts. If possible, I want to read file with a minimal waste of time.


回答1:


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.

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



回答2:


You should try to use a BufferedInputStream around your FileInputStream. 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.




回答3:


There are useful utilities in FileUtils for reading a file at once. This is simpler and efficient for modest files up to 100 MB.

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


来源:https://stackoverflow.com/questions/6277508/how-can-i-read-from-a-binary-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!