开发者

how can i read from a binary file?

开发者 https://www.devze.com 2023-03-11 23:47 出处:网络
I want to read a binary file that its size is 5.5 megabyte(a mp3 file). I tried i开发者_JAVA技巧t with fileinputstream but it took many attempts. If possible, I want to read file with a minimal waste

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


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.


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消