将文件转换为字节数组,反之亦然 [英] Convert file to byte array and vice versa

查看:117
本文介绍了将文件转换为字节数组,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了很多方法将文件转换为字节数组并将字节数组写入存储文件。

I've found many ways of converting a file to a byte array and writing byte array to a file on storage.

我想要的是转换 java.io.File 到一个字节数组,然后将一个字节数组转换回 java.io.File

What I want is to convert java.io.File to a byte array and then convert a byte array back to a java.io.File.

我不想把它写到存储器中,如下所示:

I don't want to write it out to storage like the following:

//convert array of bytes into file
FileOutputStream fileOuputStream = new FileOutputStream("C:\\testing2.txt"); 
fileOuputStream.write(bFile);
fileOuputStream.close();

我想以某种方式执行以下操作:

I want to somehow do the following:

File myFile = ConvertfromByteArray(bytes);


推荐答案

我认为你误解了 java.io.File 类确实代表。它只是系统上文件的表示,即它的名称,路径等。

I think you misunderstood what the java.io.File class really represents. It is just a representation of the file on your system, i.e. its name, its path etc.

您是否甚至查看了的Javadoc java.io.File class?看看这里
如果你检查它有的字段或方法或构造函数参数,你立即得到它的全部提示,是URL /路径的表示。

Did you even look at the Javadoc for the java.io.File class? Have a look here If you check the fields it has or the methods or constructor arguments, you immediately get the hint that all it is, is a representation of the URL/path.

Oracle提供了相当的他们的 Java文件I / O教程中的大量教程,最新的NIO.2功能。

Oracle provides quite an extensive tutorial in their Java File I/O tutorial, with the latest NIO.2 functionality too.

使用NIO.2,您可以使用 java.nio.file.Files.readAllBytes()

With NIO.2 you can read it in one line using java.nio.file.Files.readAllBytes().

同样可以使用 java.nio.file.Files.write ()写入字节中的所有字节数组。

Similarly you can use java.nio.file.Files.write() to write all bytes in your byte array.

更新

由于问题标记为Android,因此更为传统方法是将 FileInputStream 包装在 BufferedInputStream 中,然后将其包装在 ByteArrayInputStream中
这将允许您读取 byte [] 中的内容。类似地,它们的对应物存在于 OutputStream

Since the question is tagged Android, the more conventional way is to wrap the FileInputStream in a BufferedInputStream and then wrap that in a ByteArrayInputStream. That will allow you to read the contents in a byte[]. Similarly the counterparts to them exist for the OutputStream.

这篇关于将文件转换为字节数组,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆