问题描述
是否可以在文件实例上获取和设置自定义元数据?我想将通过系统处理的文件用作一种非常简单的数据库,其中每个文件都应包含其他自定义元数据,例如发件人的电子邮件,一些时间戳等.
Is it possible to get and set custom metadata on File instances? I want to use the files that I process through my system as some kind of a very simple database, where every file should contain additional custom metadata, such as the email of the sender, some timestamps, etc.
它用于内部系统,因此安全性不是问题.
It is for an internal system, so security is not an issue.
推荐答案
在Java 7中,您可以使用类和UserDefinedFileAttributeView
.
In java 7 you can do this using the Path
class and UserDefinedFileAttributeView
.
这里是从那里获取的示例:
Here is the example taken from there:
使用以下代码段,可以将文件的MIME类型存储为用户定义的属性:
A file's MIME type can be stored as a user-defined attribute by using this code snippet:
Path file = ...;
UserDefinedFileAttributeView view = Files
.getFileAttributeView(file, UserDefinedFileAttributeView.class);
view.write("user.mimetype",
Charset.defaultCharset().encode("text/html");
要读取MIME类型属性,请使用以下代码段:
To read the MIME type attribute, you would use this code snippet:
Path file = ...;
UserDefinedFileAttributeView view = Files
.getFileAttributeView(file,UserDefinedFileAttributeView.class);
String name = "user.mimetype";
ByteBuffer buf = ByteBuffer.allocate(view.size(name));
view.read(name, buf);
buf.flip();
String value = Charset.defaultCharset().decode(buf).toString();
这篇关于是否可以使用Java在文件上设置自定义元数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!