简体   繁体   English

Java加载二进制文件

[英]Java loading binary files

Please show me the best/fast methods for: 请告诉我最好/最快的方法:

1) Loading very small binary files into memory. 1)将很小的二进制文件加载到内存中。 For example icons; 例如图标;

2) Loading/reading very big binary files of size 512Mb+. 2)加载/读取大小为512Mb +的非常大的二进制文件。 Maybe i must use memory-mapped IO? 也许我必须使用内存映射的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? 3)当您不想考虑大小/速度而只能做的事情时,您通常会选择:将所有字节读入内存吗?

Thank you!!! 谢谢!!!

PS Sorry for maybe trivial question. PS对不起,也许是一个琐碎的问题。 Please do not close it;) 请不要关闭它;)

PS2. PS2。 Mirror of analog question for C#; C#模拟问题的镜像

For memory mapped files, java has a nio package: Memory Mapped Files 对于内存映射文件,java有一个nio包: Memory Mapped Files

Check out byte stream class for small files: Byte Stream 检出小文件的字节流类: 字节流

Check out buffered I/O for larger files: Buffered Stream 检出较大文件的缓冲I / O: 缓冲流

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. 在现实生活中,如果发生I / O错误,则需要一些try / catch块。

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. 这是一个非常罕见的应用程序,确实需要一次将500MB文件全部保存在内存中。

There is no such thing as memory-mapped I/O in Java. Java中没有内存映射的I / O。 If that's what you need to do, you'd just have to create a really big byte array. 如果这是您需要做的,则只需创建一个非常大的字节数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM