获取文件元数据字段

时间:2014-09-16 20:57:44

标签: java windows file metadata

我正在使用此代码在图像文件中获取特定的用户定义元数据:

File file = new File("C:\\image.jpg");
        Path path = FileSystems.getDefault().getPath(file.getPath(), "");
        BasicFileAttributes attr = null;
        try {
            attr = Files.readAttributes(path, BasicFileAttributes.class);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        UserDefinedFileAttributeView view = Files
        .getFileAttributeView(path,UserDefinedFileAttributeView.class);
        String name = "UserDefinedField";

        ByteBuffer buf = null;
        try {
            buf = ByteBuffer.allocate(view.size(name));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            view.read(name, buf);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        buf.flip();
        String value = Charset.defaultCharset().decode(buf).toString();
        System.out.println(value);

但我必须知道该字段,有没有办法列出所有元数据字段?!

1 个答案:

答案 0 :(得分:1)

您可以使用list()来检索文件的所有UserDefinedFileAttributes,如

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.UserDefinedFileAttributeView;
import java.util.List;

public class ReadData {

    public static void main(String[] args) throws IOException {
        Path path = Paths.get("someImage.jpg").toAbsolutePath();

        UserDefinedFileAttributeView fileAttributeView = Files.getFileAttributeView(path, UserDefinedFileAttributeView.class);
        List<String> allAttrs = fileAttributeView.list();

        for (String att : allAttrs) {
            System.out.println("att = " + att);
        }
    }
}