Java loading binary files

淺唱寂寞╮ 提交于 2019-12-01 13:23:23

问题


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.



来源:https://stackoverflow.com/questions/4246360/java-loading-binary-files

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