sun.nio.fs.AbstractUserDefinedFileAttributeView.setAttribute(Unknown Source)异常

时间:2013-11-12 11:57:24

标签: java

我没有得到如何为所有文件类型添加自定义元数据,如txt,doc,docx,xl​​s,xlsx,ppt,pptx,pdf等 我已尝试使用File类setAttribute()方法获取txt文件,但我收到错误。

Path path = new File("C:\\Users\\a.txt").toPath();

        try{

         Files.setAttribute(path, "user:custom_attribute", "value1");
         }catch(IOException e){

            System.out.println(e.getMessage());
        }

我没有得到我错的地方......我收到以下错误

     java.lang.String cannot be cast to java.nio.ByteBuffer
at sun.nio.fs.AbstractUserDefinedFileAttributeView.setAttribute(Unknown Source)
at sun.nio.fs.AbstractFileSystemProvider.setAttribute(Unknown Source)
at java.nio.file.Files.setAttribute(Unknown Source)

2 个答案:

答案 0 :(得分:0)

您可以使用UserDefinedFileAttributeView来定义自定义属性:

final UserDefinedFileAttributeView view = Files.getFileAttributeView(path, UserDefinedFileAttributeView.class);
view.write("user.custom attribute", Charset.defaultCharset().encode("text/html"));

答案 1 :(得分:0)

属性存储为字节序列,因此setAttribute需要一个字节序列。如果要存储String,则必须使用定义的字符集对其进行转换。

try
{
  ByteBuffer bb=StandardCharsets.UTF_8.encode("value1");
  Files.setAttribute(path, "user:custom_attribute", bb);
} catch(IOException e)
{
  System.out.println(e.getMessage());
}

再次获取值需要从字节转换为String

try
{
  byte[] b=(byte[])Files.getAttribute(path, "user:custom_attribute");
  String value=StandardCharsets.UTF_8.decode(ByteBuffer.wrap(b)).toString();
  System.out.println(value);
} catch(IOException e)
{
  System.out.println(e.getMessage());
}
相关问题