Java loading binary files

2020-04-02 06:15发布

问题:

Please show me the best/fast methods for:

1) Loading very small binary files into memory. For example icons;

2) Loading/reading very big binary files of size 512Mb+. Maybe i must use memory-mapped IO?

3) Your common choice when you do not want to think about size/speed but must do only thing: read all bytes into memory?

Thank you!!!

P.S. Sorry for maybe trivial question. Please do not close it;)

P.S.2. Mirror of analog question for C#;

回答1:

For memory mapped files, java has a nio package: Memory Mapped Files

Check out byte stream class for small files:Byte Stream

Check out buffered I/O for larger files: Buffered Stream



回答2:

The simplest way to read a small file into memory is:

// Make a file object from the path name
File file=new File("mypath");
// Find the size
int size=file.length();
// Create a buffer big enough to hold the file
byte[] contents=new byte[size];
// Create an input stream from the file object
FileInputStream in=new FileInutStream(file);
// Read it all
in.read(contents);
// Close the file
in.close();

In real life you'd need some try/catch blocks in case of I/O errors.

If you're reading a big file, I would strongly suggest NOT reading it all into memory at one time if it can possibly be avoided. Read it and process it in chunks. It's a very rare application that really needs to hold a 500MB file in memory all at once.

There is no such thing as memory-mapped I/O in Java. If that's what you need to do, you'd just have to create a really big byte array.