本文正在参加「Java主题月 - Java Debug笔记活动」,详情查看活动链接
如果将文件转换Java中的byte []?
如何将a转换java.io.File为a byte[]?
高分回答:
这取决于最适合您的方式。明智地提高生产力,不要重蹈覆辙,而是使用Apache Commons。
FileUtils.readFileToByteArray(File input)。
高分回答:
基本上,您必须在内存中读取它。打开文件,分配数组,然后将文件中的内容读入数组。
最简单的方法类似于以下内容:
public byte[] read(File file) throws IOException, FileTooBigException {
if (file.length() > MAX_FILE_SIZE) {
throw new FileTooBigException(file);
}
ByteArrayOutputStream ous = null;
InputStream ios = null;
try {
byte[] buffer = new byte[4096];
ous = new ByteArrayOutputStream();
ios = new FileInputStream(file);
int read = 0;
while ((read = ios.read(buffer)) != -1) {
ous.write(buffer, 0, read);
}
}finally {
try {
if (ous != null)
ous.close();
} catch (IOException e) {
}
try {
if (ios != null)
ios.close();
} catch (IOException e) {
}
}
return ous.toByteArray();
}
这对文件内容有一些不必要的复制(实际上,数据被复制了3次:从文件到buffer,从buffer到ByteArrayOutputStream,从ByteArrayOutputStream到实际的结果数组)。
您还需要确保仅在内存中读取最大大小的文件(这通常取决于应用程序):-)。
您还需要对待IOException外部函数。
另一种方法是这样的:
public byte[] read(File file) throws IOException, FileTooBigException {
if (file.length() > MAX_FILE_SIZE) {
throw new FileTooBigException(file);
}
byte[] buffer = new byte[(int) file.length()];
InputStream ios = null;
try {
ios = new FileInputStream(file);
if (ios.read(buffer) == -1) {
throw new IOException(
"EOF reached while trying to read the whole file");
}
} finally {
try {
if (ios != null)
ios.close();
} catch (IOException e) {
}
}
return buffer;
}
这没有不必要的复制。
FileTooBigException是自定义应用程序异常。该MAX_FILE_SIZE常数是一个应用程序参数。
对于大文件,您可能应该考虑使用流处理算法或使用内存映射(请参阅参考资料java.nio)。
文章翻译自 am2dgbqfb6mk75jcyanzabc67y-ac4c6men2g7xr2a-stackoverflow-com.translate.goog/questions/8…
作者建议: 关于文件的读写和转换,之前已经译过很多篇文章了,在这里我建议使用MMAP + FileChannel 来实现。
可以看到,FileChannel的性能是比较高的。
我参考了mmap + FileChannel的相关测试,发现会更好。
简单说一下,就拿比较火热的rocketMQ来说,它是文件系统来存储数据的,生产和消费数据都是直接操作的文件,它会涉及到页缓存、FileChannel、FileChannel一次性读取1页4kb的数据,高性能得益于ByteBuffer 缓冲区、MMAP内存映射
RokcetMQ为了更好的性能也进行了调优
预分配MappedFile
mlock系统调用
文件预热
顺序读、顺序写
我这里只是进行一个抛砖引玉,大家加油!
真心感谢帅逼靓女们能看到这里,如果这个文章写得还不错,觉得有点东西的话
求点赞👍 求关注❤️ 求分享👥 对8块腹肌的我来说真的 非常有用!!!
如果本篇博客有任何错误,请批评指教,不胜感激 !❤️❤️❤️❤️