Skip to content

Instantly share code, notes, and snippets.

@ajaysjournal
Created March 19, 2017 15:14
Show Gist options
  • Save ajaysjournal/e21d6159d8271fe0a4cfaf7209f6fb74 to your computer and use it in GitHub Desktop.
Save ajaysjournal/e21d6159d8271fe0a4cfaf7209f6fb74 to your computer and use it in GitHub Desktop.
package examples;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
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;
/**
* Created by Ajay on 3/19/17.
*/
public class UserDefinedFileAttributeExample {
public static void main(String[] args) throws IOException {
Path path = Paths.get("temp.txt");
nioUserDefinedFileAttributeView(path);
}
public static void nioUserDefinedFileAttributeView(Path path)
throws IOException {
if (File.separatorChar != '\\') {
System.out.println("This is Windows specific and so exit!");
return;
}
UserDefinedFileAttributeView userDefinedFAView = Files
.getFileAttributeView(path, UserDefinedFileAttributeView.class);
List<String> attributeList = userDefinedFAView.list();
System.out.println("User Defined Attribute List Size Before Adding: "
+ attributeList.size());
// set user define attribute
String attributeName = "foo";
String attributeValue = "bar";
userDefinedFAView.write(attributeName,
Charset.defaultCharset().encode(attributeValue));
attributeList = userDefinedFAView.list();
if (attributeList.size() > 0) {
for (String attName : attributeList) {
ByteBuffer attValue = ByteBuffer.allocate(userDefinedFAView
.size(attName));
userDefinedFAView.read(attName, attValue);
attValue.flip();
System.out.println("User Defined Attribute Name: " + attName);
System.out.println("User Defined Attribute Value: "
+ Charset.defaultCharset().decode(attValue).toString());
}
} else {
System.out
.println("User define attribute count should be at least 1"
+ " as we have set an attribute just now!");
}
userDefinedFAView.delete(attributeName);
// And list the attributes again to check they're back to 0
attributeList = userDefinedFAView.list();
System.out.println("User Defined Attribute List Size After Deleting: "
+ attributeList.size());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment