如何从文件的字节数组中获取文件名? [英] How to get a file name from a file's byte array?
问题描述
我有代表我通过网络传输的文件的字节.除了在文件系统上手动重建文件外,如何从文件中获取信息,例如getName()、getPath()等?
I have the bytes representing a file that I am transmitting over a network. Besides reconstructing the file manually on the file system, how can I get the information from the File, such as getName(), getPath(), etc?
换句话说:
- 我从机器 A 上的文件开始
- 我使用 FileUtils 将文件转换为字节数组
- 我通过网络将该文件传输到机器 B
- 在机器 B 上,我想将该 byte[] 重构为一个 File 并运行诸如 getName() 之类的方法
以下不起作用
- (文件)字节 --> 不转换
- ((File) ((Object) bytes))) --> 也不转换
我真的不想在文件系统上创建一个新的临时文件,尽管我知道有静态 File.createTemp 可以做到这一点.我更愿意将它保存在内存中,从 byte[] 数组构造一个新的 File 对象,获取我需要的信息并完成.
I would really rather not create a new temporary file on the filesytem, although I know there are static File.createTemp available that will do that. I'd prefer to just keep it in memory, construct a new File object from the byte[] array, get the information I Need and be done.
实际上,更好的是 API 将获取 byte[] 并从中通过解析位直接获取文件名.
Actually, what would be even better is an API that will take the byte[] and from it, directly get the file name by parsing the bits.
推荐答案
FileUtils.readFileToByteArray
返回的 byte[]
只是文件内容,没有别的.
The byte[]
that is returned by FileUtils.readFileToByteArray
is only the file contents, nothing else.
您应该创建自己的可序列化类,该类包括两个字段:用于文件内容的 byte[]
和包含所有内容的 java.io.File
否则你需要.然后将您的类序列化/反序列化为 byte[]
,然后传输.
You should create your own class that is Serializable that includes two fields: a byte[]
for the file contents, and a java.io.File
that has everything else you need. You then serialize/deserialize your class into byte[]
, which is transmitted.
这篇关于如何从文件的字节数组中获取文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!