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

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

问题描述

我发现了许多将文件转换为字节数组并将字节数组写入存储文件的方法.

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.

您是否甚至查看了 java.io.File 类的 Javadoc?看看这里如果您检查它具有的字段或方法或构造函数参数,您会立即得到提示,即它只是 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天全站免登陆