下面列出了怎么用java.nio.file.attribute.UserDefinedFileAttributeView的API类实例代码及写法,或者点击链接到github查看源代码。
public boolean setMetadata(Path file, String key, String value) {
if (supportsUserDefinedAttributes(file)) {
UserDefinedFileAttributeView view = Files.getFileAttributeView(file, UserDefinedFileAttributeView.class);
try {
if (value != null) {
view.write(key, Charset.defaultCharset().encode(value));
} else {
view.delete(key);
}
return true;
} catch (IOException e) {
return false;
}
}
return false;
}
/**
* Set an user extended attribute for the given file.
*
* @param attr the attribut consist of the name and the value in the format
* {@code name=value}
* @param file the filename for which the attribut should be set
*/
private static void setXattr(String attr, String file) {
UserDefinedFileAttributeView view = getAttributeView(file);
String[] xattr = attr.split("=");
if (xattr.length < 2) {
System.out.println("the extended attribute and value must follow the format: name=value");
return;
}
String name = xattr[0];
String value = xattr[1];
try {
view.write(name, Charset.defaultCharset().encode(value));
} catch (Exception ex) {
System.out.printf("could not set attr '%s=%s' for %s%n%s%n", name, value, file, ex);
}
}
/**
* Show the value of a user extended attribut stored on the given file.
*
* @param name the name of the user extended attribute
* @param file the filename from which the attribute should be read
* @throws IOException when the user extended attribute information could
* not be read
*/
private static void getXattr(String name, String file) {
UserDefinedFileAttributeView view = getAttributeView(file);
try {
Charset defaultCharset = Charset.defaultCharset();
if (view.list().contains(name)) {
System.out.printf("# file: %s%n", file);
String value = getAttrValue(view, name);
System.out.printf("user.%s=\"%s\"%n", name, value);
} else {
System.out.printf("file has no extended attribute [%s]%n", name);
}
} catch (IOException ex) {
System.out.printf("failed to get the extended attribute %s from %s%n", name, file);
}
}
private long getInode(File file) throws IOException {
UserDefinedFileAttributeView view = null;
// windows system and file customer Attribute
if (OS_WINDOWS.equals(os)) {
view = Files.getFileAttributeView(file.toPath(), UserDefinedFileAttributeView.class);// 把文件的内容属性值放置在view里面?
try {
ByteBuffer buffer = ByteBuffer.allocate(view.size(INODE));// view.size得到inode属性值大小
view.read(INODE, buffer);// 把属性值放置在buffer中
buffer.flip();
return Long.parseLong(Charset.defaultCharset().decode(buffer).toString());// 返回编码后的inode的属性值
}
catch (NoSuchFileException e) {
long winode = random.nextLong();
view.write(INODE, Charset.defaultCharset().encode(String.valueOf(winode)));
return winode;
}
}
long inode = (long) Files.getAttribute(file.toPath(), "unix:ino");// 返回unix的inode的属性值
return inode;
}
/**
* Test: File and FileStore attributes
*/
@Test
public void testFileStoreAttributes() throws URISyntaxException, IOException {
URI uri = clusterUri.resolve("/tmp/testFileStore");
Path path = Paths.get(uri);
if (Files.exists(path))
Files.delete(path);
assertFalse(Files.exists(path));
Files.createFile(path);
assertTrue(Files.exists(path));
FileStore store1 = Files.getFileStore(path);
assertNotNull(store1);
assertTrue(store1.supportsFileAttributeView("basic"));
assertTrue(store1.supportsFileAttributeView(BasicFileAttributeView.class));
assertTrue(store1.supportsFileAttributeView("posix") == store1
.supportsFileAttributeView(PosixFileAttributeView.class));
assertTrue(store1.supportsFileAttributeView("dos") == store1
.supportsFileAttributeView(DosFileAttributeView.class));
assertTrue(store1.supportsFileAttributeView("acl") == store1
.supportsFileAttributeView(AclFileAttributeView.class));
assertTrue(store1.supportsFileAttributeView("user") == store1
.supportsFileAttributeView(UserDefinedFileAttributeView.class));
}
Optional<Long> readFileAttributeAsLong(
Path file,
String attribute,
UserDefinedFileAttributeView view,
List<String> knownAttributes
) {
if (knownAttributes.contains(attribute)) {
try {
LOG.trace("Attempting to read attribute {}, from file {}", attribute, file);
ByteBuffer buf = ByteBuffer.allocate(view.size(attribute));
view.read(attribute, buf);
buf.flip();
String value = Charset.defaultCharset().decode(buf).toString();
if (Strings.isNullOrEmpty(value)) {
LOG.debug("No attrbiute {} found for file {}", attribute, file);
return Optional.empty();
}
return Optional.of(Long.parseLong(value));
} catch (Exception e) {
LOG.error("Error getting extra file metadata for {}", file, e);
return Optional.empty();
}
} else {
return Optional.empty();
}
}
@Test
public void computeSha1ViaXattrForFileUnderMount() throws IOException {
FileSystem fs =
Jimfs.newFileSystem(Configuration.unix().toBuilder().setAttributeViews("user").build());
Path root = fs.getPath(JIMFS_WORKING_DIRECTORY);
ProjectFilesystemDelegate delegate = new DefaultProjectFilesystemDelegate(root);
Path path = fs.getPath("/foo");
Files.createFile(path);
UserDefinedFileAttributeView view =
Files.getFileAttributeView(path, UserDefinedFileAttributeView.class);
ByteBuffer buf = ByteBuffer.wrap(DUMMY_SHA1.toString().getBytes(StandardCharsets.UTF_8));
view.write("sha1", buf);
EdenMount mount = createMock(EdenMount.class);
Config config = ConfigBuilder.createFromText("[eden]", "use_xattr = true");
EdenProjectFilesystemDelegate edenDelegate =
new EdenProjectFilesystemDelegate(mount, delegate, config);
assertEquals(DUMMY_SHA1, edenDelegate.computeSha1(path));
}
@Test
public void computeSha1ViaXattrForFileUnderMountInvalidUTF8() throws IOException {
FileSystem fs =
Jimfs.newFileSystem(Configuration.unix().toBuilder().setAttributeViews("user").build());
Path root = fs.getPath(JIMFS_WORKING_DIRECTORY);
ProjectFilesystemDelegate delegate = new DefaultProjectFilesystemDelegate(root);
Path path = fs.getPath("/foo");
Files.createFile(path);
byte[] bytes = new byte[] {66, 85, 67, 75};
Files.write(path, bytes);
UserDefinedFileAttributeView view =
Files.getFileAttributeView(path, UserDefinedFileAttributeView.class);
ByteBuffer buf = ByteBuffer.allocate(2);
buf.putChar((char) 0xfffe);
view.write("sha1", buf);
EdenMount mount = createMock(EdenMount.class);
Config config = ConfigBuilder.createFromText("[eden]", "use_xattr = true");
EdenProjectFilesystemDelegate edenDelegate =
new EdenProjectFilesystemDelegate(mount, delegate, config);
assertEquals(
"EdenProjectFilesystemDelegate.computeSha1() should return the SHA-1 of the contents",
Sha1HashCode.fromHashCode(Hashing.sha1().hashBytes(bytes)),
edenDelegate.computeSha1(path));
}
public String getMetadata(Path file, String key) {
if (supportsUserDefinedAttributes(file)) {
UserDefinedFileAttributeView view = Files.getFileAttributeView(file, UserDefinedFileAttributeView.class);
try {
ByteBuffer bb = ByteBuffer.allocate(view.size(key));
view.read(key, bb);
bb.flip();
return Charset.defaultCharset().decode(bb).toString();
} catch (IOException e) {
return null;
}
}
return null;
}
protected boolean supportsUserDefinedAttributes(Path file) {
try {
return Files.getFileStore(file).supportsFileAttributeView(UserDefinedFileAttributeView.class);
} catch (IOException e) {
return false;
}
}
public static void setXattr(Map<String, String> attrs, String fullPath) throws IOException {
UserDefinedFileAttributeView view = getAttributeView(fullPath);
for (Map.Entry<String, String> entry : attrs.entrySet()) {
view.write(entry.getKey(), Charset.defaultCharset().encode(entry.getValue()));
}
}
public static String getXattr(String name, String fullPath) throws IOException {
String value = null;
UserDefinedFileAttributeView view = getAttributeView(fullPath);
if (view.list().contains(name)) {
value = getAttrValue(view, name);
}
return value;
}
public static Map<String, String> getAllXattr(String fullPath) throws IOException {
Map<String, String> values = Maps.newHashMap();
UserDefinedFileAttributeView view = getAttributeView(fullPath);
for (String name : view.list()) {
String value = getAttrValue(view, name);
values.put(name, value);
}
return values;
}
private static String getAttrValue(UserDefinedFileAttributeView view, String name) throws IOException {
int attrSize = view.size(name);
ByteBuffer buffer = ByteBuffer.allocateDirect(attrSize);
view.read(name, buffer);
buffer.flip();
return Charset.defaultCharset().decode(buffer).toString();
}
private static UserDefinedFileAttributeView getAttributeView(String fullPath) {
UserDefinedFileAttributeView view = Files.getFileAttributeView(Paths.get(fullPath),
UserDefinedFileAttributeView.class);
if(view==null){
throw new RuntimeException("The attribute view type is not available");
}else {
return view;
}
}
/**
* List all user extended attributes and their related values for the given
* file.
*
* @throws IOException when the user extended attribute information could
* not be read
*/
private static void dumpAllXattr(String file) {
UserDefinedFileAttributeView view = getAttributeView(file);
System.out.printf("# file: %s%n", file);
try {
for (String name : view.list()) {
String value = getAttrValue(view, name);
System.out.printf("user.%s=\"%s\"%n", name, value);
}
} catch (IOException ex) {
System.out.printf("failed to get the extended attribute informations from %s%n", file);
}
}
/**
* Delete a user extended attribute from the given file.
*
* @param name the name of the attribute which should be deleted
* @param file the filename from which the attribute should be deleted
* @throws IOException when the user extended attribute information could
* not be read
*/
private static void delXattr(String name, String file) {
UserDefinedFileAttributeView view = getAttributeView(file);
try {
view.delete(name);
} catch (IOException ex) {
System.out.println("failed to delete the user extended attribute: " + ex.getMessage());
}
}
/**
* Test for bug 240953 - Netbeans Deletes User Defined Attributes.
*
* @throws java.io.IOException
*/
public void testWritingKeepsFileAttributes() throws IOException {
final String attName = "User_Attribute";
final String attValue = "User_Attribute_Value";
if (Utilities.isWindows()) {
clearWorkDir();
File f = new File(getWorkDir(), "fileWithAtts.txt");
f.createNewFile();
UserDefinedFileAttributeView attsView = Files.getFileAttributeView(
f.toPath(), UserDefinedFileAttributeView.class);
ByteBuffer buffer = Charset.defaultCharset().encode(attValue);
attsView.write(attName, buffer);
buffer.rewind();
attsView.read(attName, buffer);
buffer.flip();
String val = Charset.defaultCharset().decode(buffer).toString();
assertEquals(attValue, val);
FileObject fob = FileUtil.toFileObject(f);
OutputStream os = fob.getOutputStream();
try {
os.write(55);
} finally {
os.close();
}
buffer.rewind();
attsView.read(attName, buffer);
buffer.flip();
String val2 = Charset.defaultCharset().decode(buffer).toString();
assertEquals(attValue, val2);
}
}
public static void setExecutable ( final Path path, final boolean state ) throws IOException
{
final UserDefinedFileAttributeView ua = Files.getFileAttributeView ( path, UserDefinedFileAttributeView.class );
if ( state )
{
ua.write ( ATTR_EXECUTE, ByteBuffer.wrap ( marker ) );
}
else
{
ua.delete ( ATTR_EXECUTE );
}
}
public static boolean getExecutable ( final Path path ) throws IOException
{
final UserDefinedFileAttributeView ua = Files.getFileAttributeView ( path, UserDefinedFileAttributeView.class );
if ( !ua.list ().contains ( ATTR_EXECUTE ) )
{
// check first, otherwise the size() call with give an exception
return false;
}
final ByteBuffer buf = ByteBuffer.allocate ( ua.size ( ATTR_EXECUTE ) );
ua.read ( ATTR_EXECUTE, buf );
buf.flip ();
return Boolean.parseBoolean ( CHARSET.decode ( buf ).toString () );
}
@Test
public void setCustomerAttr() throws IOException {
Path target = Paths.get("/Users/fathead/temp/file4");
UserDefinedFileAttributeView view = Files.getFileAttributeView(target, UserDefinedFileAttributeView.class);
view.write(name, Charset.defaultCharset().encode("pinelet"));
}
@Test
public void getCustomerAttr() throws IOException {
Path target = Paths.get("/Users/fathead/temp/file4");
UserDefinedFileAttributeView view2 = Files.getFileAttributeView(target, UserDefinedFileAttributeView.class);
ByteBuffer buf = ByteBuffer.allocate(view2.size(name));
view2.read(name, buf);
buf.flip();
String value = Charset.defaultCharset().decode(buf).toString();
System.out.println("value=" + value);
}
UploaderFileAttributes getFileAttributes(Path file) {
Set<String> supportedViews = FileSystems.getDefault().supportedFileAttributeViews();
LOG.trace("Supported attribute views are {}", supportedViews);
if (supportedViews.contains("user")) {
try {
UserDefinedFileAttributeView view = Files.getFileAttributeView(
file,
UserDefinedFileAttributeView.class
);
List<String> attributes = view.list();
LOG.debug("Found file attributes {} for file {}", attributes, file);
Optional<Long> maybeStartTime = readFileAttributeAsLong(
file,
LOG_START_TIME_ATTR,
view,
attributes
);
Optional<Long> maybeEndTime = readFileAttributeAsLong(
file,
LOG_END_TIME_ATTR,
view,
attributes
);
return new UploaderFileAttributes(maybeStartTime, maybeEndTime);
} catch (Exception e) {
LOG.error("Could not get extra file metadata for {}", file, e);
}
}
return new UploaderFileAttributes(Optional.empty(), Optional.empty());
}
public static void delXattr(String name, String file) throws IOException {
UserDefinedFileAttributeView view = getAttributeView(file);
view.delete(name);
}
@Override
public Class<UserDefinedFileAttributeView> viewType() {
return UserDefinedFileAttributeView.class;
}
@Override
public UserDefinedFileAttributeView view(
FileLookup lookup, ImmutableMap<String, FileAttributeView> inheritedViews) {
return new View(lookup);
}
/**
* @param view the attribute view of the extendet attribute for a specific
* file
* @param name the name of the attribute for which the value should be
* returned
* @return the value of an user extended attribute from the given attribute
* view
*/
private static String getAttrValue(UserDefinedFileAttributeView view, String name) throws IOException {
int attrSize = view.size(name);
ByteBuffer buffer = ByteBuffer.allocateDirect(attrSize);
view.read(name, buffer);
buffer.flip();
return Charset.defaultCharset().decode(buffer).toString();
}
/**
* @return if the passed {@link FileStore} has support for user extended
* attributes
*/
private static boolean hasUserXattrSupport(FileStore fileStore) {
return fileStore.supportsFileAttributeView(UserDefinedFileAttributeView.class);
}
/**
* Returns the attribute view of the extended attribute for the given file.
*
* @param file the filename for which the attribute view should be returned
* @return
*/
private static UserDefinedFileAttributeView getAttributeView(String file) {
return Files.getFileAttributeView(Paths.get(file),
UserDefinedFileAttributeView.class);
}