1

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#;

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

Comments

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.

3 Comments

read isn't guarenteed to read all at once. I would suggest using DataInputyStream.readFully();
JDK 1.4 and later provide nio, and I think MappedByteBuffer should work as memory-mapped I/O.
Okay, I wasn't familiar with that class. It isn't really memory-mapped I/O, at least not as I understood the term back in my pre-Windows days where I/O ports were mapped to magic memory locations. It's more like simulated array-mapped I/O. But whatever. If it works for you, cool.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.