Java Code Examples for java.nio.file.attribute.BasicFileAttributeView

The following examples show how to use java.nio.file.attribute.BasicFileAttributeView. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: SENS   Source File: SensUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * 获取文件创建时间
 *
 * @param srcPath 文件绝对路径
 * @return 时间
 */
public static Date getCreateTime(String srcPath) {
    Path path = Paths.get(srcPath);
    BasicFileAttributeView basicview = Files.getFileAttributeView(path, BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
    BasicFileAttributes attr;
    try {
        attr = basicview.readAttributes();
        Date createDate = new Date(attr.creationTime().toMillis());
        return createDate;
    } catch (Exception e) {
        e.printStackTrace();
    }
    Calendar cal = Calendar.getInstance();
    cal.set(1970, 0, 1, 0, 0, 0);
    return cal.getTime();
}
 
Example 2
Source Project: stone   Source File: HaloUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * 获取文件创建时间
 *
 * @param srcPath 文件绝对路径
 *
 * @return 时间
 */
public static Date getCreateTime(String srcPath) {
    final Path path = Paths.get(srcPath);
    final BasicFileAttributeView basicview = Files.getFileAttributeView(path, BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
    BasicFileAttributes attr;
    try {
        attr = basicview.readAttributes();
        final Date createDate = new Date(attr.creationTime().toMillis());
        return createDate;
    } catch (Exception e) {
        e.printStackTrace();
    }
    final Calendar cal = Calendar.getInstance();
    cal.set(1970, 0, 1, 0, 0, 0);
    return cal.getTime();
}
 
Example 3
Source Project: blog-sharon   Source File: HaloUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 获取文件创建时间
 *
 * @param srcPath 文件绝对路径
 * @return 时间
 */
public static Date getCreateTime(String srcPath) {
    Path path = Paths.get(srcPath);
    BasicFileAttributeView basicview = Files.getFileAttributeView(path, BasicFileAttributeView.class,
            LinkOption.NOFOLLOW_LINKS);
    BasicFileAttributes attr;
    try {
        attr = basicview.readAttributes();
        Date createDate = new Date(attr.creationTime().toMillis());
        return createDate;
    } catch (Exception e) {
        e.printStackTrace();
    }
    Calendar cal = Calendar.getInstance();
    cal.set(1970, 0, 1, 0, 0, 0);
    return cal.getTime();
}
 
Example 4
Source Project: jimfs   Source File: AttributeServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("ConstantConditions")
@Test
public void testGetFileAttributeView() throws IOException {
  final File file = Directory.create(0);
  service.setInitialAttributes(file);

  FileLookup fileLookup =
      new FileLookup() {
        @Override
        public File lookup() throws IOException {
          return file;
        }
      };

  assertThat(service.getFileAttributeView(fileLookup, TestAttributeView.class)).isNotNull();
  assertThat(service.getFileAttributeView(fileLookup, BasicFileAttributeView.class)).isNotNull();

  TestAttributes attrs =
      service.getFileAttributeView(fileLookup, TestAttributeView.class).readAttributes();
  assertThat(attrs.foo()).isEqualTo("hello");
  assertThat(attrs.bar()).isEqualTo(0);
  assertThat(attrs.baz()).isEqualTo(1);
}
 
Example 5
Source Project: mycore   Source File: MCRFileSystemProvider.java    License: GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <V extends FileAttributeView> V getFileAttributeView(Path path, Class<V> type, LinkOption... options) {
    MCRPath mcrPath = MCRFileSystemUtils.checkPathAbsolute(path);
    if (type == null) {
        throw new NullPointerException();
    }
    //must support BasicFileAttributeView
    if (type == BasicFileAttributeView.class) {
        return (V) new BasicFileAttributeViewImpl(mcrPath);
    }
    if (type == MCRMD5AttributeView.class) {
        return (V) new MD5FileAttributeViewImpl(mcrPath);
    }
    return null;
}
 
Example 6
Source Project: mycore   Source File: MCRDirectoryStream.java    License: GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <V extends FileAttributeView> V getFileAttributeView(Path path, Class<V> type, LinkOption... options) {
    if (path != null) {
        MCRPath file = checkRelativePath(path);
        if (file.getNameCount() != 1) {
            throw new InvalidPathException(path.toString(), "'path' must have one name component.");
        }
    }
    checkClosed();
    if (type == null) {
        throw new NullPointerException();
    }
    //must support BasicFileAttributeView
    if (type == BasicFileAttributeView.class) {
        return (V) new BasicFileAttributeViewImpl(this, path);
    }
    if (type == MCRMD5AttributeView.class) {
        return (V) new MD5FileAttributeViewImpl(this, path);
    }
    return null;
}
 
Example 7
Source Project: xnx3   Source File: FileUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 输入文件路径,返回这个文件的创建时间
 * @param filePath 要获取创建时间的文件的路径,绝对路径
 * @return 此文件创建的时间
 */
public static Date getCreateTime(String filePath){  
	Path path=Paths.get(filePath);    
	BasicFileAttributeView basicview=Files.getFileAttributeView(path, BasicFileAttributeView.class,LinkOption.NOFOLLOW_LINKS );  
	BasicFileAttributes attr;  
	try {
		attr = basicview.readAttributes();  
		Date createDate = new Date(attr.creationTime().toMillis());  
		return createDate;  
	} catch (Exception e) {  
		e.printStackTrace();  
	}
	Calendar cal = Calendar.getInstance();  
	cal.set(1970, 0, 1, 0, 0, 0);  
	return cal.getTime();  
}
 
Example 8
Source Project: ignite   Source File: LocalIgfsSecondaryFileSystem.java    License: Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override public void setTimes(IgfsPath path, long modificationTime, long accessTime) throws IgniteException {
    Path p = fileForPath(path).toPath();

    if (!Files.exists(p))
        throw new IgfsPathNotFoundException("Failed to set times (path not found): " + path);

    try {
        Files.getFileAttributeView(p, BasicFileAttributeView.class)
            .setTimes(
                (modificationTime >= 0) ? FileTime.from(modificationTime, TimeUnit.MILLISECONDS) : null,
                (accessTime >= 0) ? FileTime.from(accessTime, TimeUnit.MILLISECONDS) : null,
                null);
    }
    catch (IOException e) {
        throw new IgniteException("Failed to set times for path: " + path, e);
    }
}
 
Example 9
Source Project: ignite   Source File: LocalFileSystemUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get POSIX attributes for file.
 *
 * @param file File.
 * @return BasicFileAttributes.
 */
@Nullable public static BasicFileAttributes basicAttributes(File file) {
    BasicFileAttributes attrs = null;

    try {
        BasicFileAttributeView view = Files.getFileAttributeView(file.toPath(), BasicFileAttributeView.class);

        if (view != null)
            attrs = view.readAttributes();
    }
    catch (IOException e) {
        throw new IgfsException("Failed to read basic file attributes: " + file.getAbsolutePath(), e);
    }

    return attrs;
}
 
Example 10
Source Project: jsr203-hadoop   Source File: TestFileStore.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testFileStore() 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 st = Files.getFileStore(path);
  assertNotNull(st);
  Assert.assertNotNull(st.name());
  Assert.assertNotNull(st.type());

  Assert.assertFalse(st.isReadOnly());

  Assert.assertNotEquals(0, st.getTotalSpace());
  Assert.assertNotEquals(0, st.getUnallocatedSpace());
  Assert.assertNotEquals(0, st.getUsableSpace());

  Assert
      .assertTrue(st.supportsFileAttributeView(BasicFileAttributeView.class));
  Assert.assertTrue(st.supportsFileAttributeView("basic"));

  st.getAttribute("test");
}
 
Example 11
Source Project: jsr203-hadoop   Source File: TestFileStore.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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));
}
 
Example 12
Source Project: jsr203-hadoop   Source File: TestFiles.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test 'basic' file view support.
 * 
 * @throws IOException
 */
@Test
public void testGetBasicFileAttributeView() throws IOException {
  Path rootPath = Paths.get(clusterUri);

  assertTrue(rootPath.getFileSystem().supportedFileAttributeViews()
      .contains("basic"));

  // Get root view
  BasicFileAttributeView view = Files.getFileAttributeView(rootPath,
      BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);

  assertNotNull(view);
  assertNotNull(view.readAttributes());
  assertNotNull(view.readAttributes().lastModifiedTime());
}
 
Example 13
Source Project: wildfly-core   Source File: PathUtil.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
private static void unzip(final ZipFile zip, final Path targetDir) throws IOException {
    final Enumeration<? extends ZipEntry> entries = zip.entries();
    while (entries.hasMoreElements()) {
        final ZipEntry entry = entries.nextElement();
        final String name = entry.getName();
        final Path current = resolveSecurely(targetDir, name);
        if (entry.isDirectory()) {
            if (!Files.exists(current)) {
                Files.createDirectories(current);
            }
        } else {
            if (Files.notExists(current.getParent())) {
                Files.createDirectories(current.getParent());
            }
            try (final InputStream eis = zip.getInputStream(entry)) {
                Files.copy(eis, current);
            }
        }
        try {
            Files.getFileAttributeView(current, BasicFileAttributeView.class).setTimes(entry.getLastModifiedTime(), entry.getLastAccessTime(), entry.getCreationTime());
        } catch (IOException e) {
            //ignore, if we cannot set it, world will not end
        }
    }
}
 
Example 14
Source Project: zip4j   Source File: FileUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testLastModifiedFileTimeForValidTimeSetsTime() throws IOException {
  Path path = mock(Path.class);
  FileSystemProvider fileSystemProvider = mockPath(path);
  BasicFileAttributeView basicFileAttributeView = mock(BasicFileAttributeView.class);
  when(fileSystemProvider.getFileAttributeView(path, BasicFileAttributeView.class))
      .thenReturn(basicFileAttributeView);

  long currentTime = System.currentTimeMillis();
  FileUtils.setFileLastModifiedTime(path, currentTime);

  verify(basicFileAttributeView).setTimes(FileTime.fromMillis(Zip4jUtil.dosToJavaTme(currentTime)), null, null);
}
 
Example 15
Source Project: zip4j   Source File: FileUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testLastModifiedFileTimeWhenIOExceptionDoesNothing() {
  Path path = mock(Path.class);
  FileSystemProvider fileSystemProvider = mockPath(path);
  when(fileSystemProvider.getFileAttributeView(path, BasicFileAttributeView.class))
      .thenThrow(new RuntimeException());

  long currentTime = System.currentTimeMillis();
  FileUtils.setFileLastModifiedTime(path, currentTime);
}
 
Example 16
Source Project: jimfs   Source File: JimfsUnixLikeFileSystemTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testMove_toDifferentFileSystem() throws IOException {
  try (FileSystem fs2 = Jimfs.newFileSystem(Configuration.unix())) {
    Path foo = fs.getPath("/foo");
    byte[] bytes = {0, 1, 2, 3, 4};
    Files.write(foo, bytes);
    Files.getFileAttributeView(foo, BasicFileAttributeView.class)
        .setTimes(FileTime.fromMillis(0), FileTime.fromMillis(1), FileTime.fromMillis(2));

    Path foo2 = fs2.getPath("/foo");
    Files.move(foo, foo2);

    assertThatPath(foo).doesNotExist();
    assertThatPath(foo2)
        .exists()
        .and()
        .attribute("lastModifiedTime")
        .is(FileTime.fromMillis(0))
        .and()
        .attribute("lastAccessTime")
        .is(FileTime.fromMillis(1))
        .and()
        .attribute("creationTime")
        .is(FileTime.fromMillis(2))
        .and()
        .containsBytes(bytes); // do this last; it updates the access time
  }
}
 
Example 17
Source Project: n4js   Source File: CommandRebuildTest.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private void setFileCreationDate(Path filePath) throws IOException {
	BasicFileAttributeView attributes = Files.getFileAttributeView(filePath, BasicFileAttributeView.class);
	FileTime time = FileTime.fromMillis(FILE_TIME_MILLISECONDS);
	attributes.setTimes(time, time, time);

	FileTime fileTime = Files.readAttributes(filePath, BasicFileAttributes.class).lastModifiedTime();
	assertEquals(FILE_TIME_MILLISECONDS, fileTime.toMillis());
}
 
Example 18
Source Project: MonitorClient   Source File: EnumFiles.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 设置属性
 * @param path 文件路径
 * @return fileConent
 */
public FileContent setAttrs(Path path) {
    try{
        if(Files.isDirectory(path))return null;
        DateFormat df = new SimpleDateFormat("yyyy/MM/dd H:m:s");
        FileContent fileContent= MonitorClientApplication.ctx.getBean(FileContent.class);
        String fileName=path.getFileName().toString();
        String dirname=path.toString().substring(0,path.toString().indexOf(fileName));
        String fileExt=fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();
        BasicFileAttributeView basicFileAttributeView=
                Files.getFileAttributeView(path,BasicFileAttributeView.class);
        fileContent.setFilePath(path.toString());//文件全路径
        fileContent.setPath(path);
        fileContent.setDirname(dirname);
        fileContent.setFileName(fileName);//文件名
        fileContent.setFileExt(fileExt);//文件后缀名
        fileContent.setExecutable(Files.isExecutable(path));//是否可执行
        fileContent.setWriteable(Files.isWritable(path));//是否可写
        fileContent.setReadable(Files.isReadable(path));//是否可读
        fileContent.setHidden(Files.isHidden(path));//是否是隐藏文件
        fileContent.setOwner(Files.getOwner(path).toString());//文件拥有者
        fileContent.setSize(Files.size(path));//文件大小
        fileContent.setLastAccessTime(//文件最后打开时间
                df.format(basicFileAttributeView.readAttributes().lastAccessTime().toMillis()));
        fileContent.setLastModifyTime(//文件最后修改时间
                df.format(basicFileAttributeView.readAttributes().lastModifiedTime().toMillis()));
        fileContent.setCreateTime(//文件创建时间
                df.format(basicFileAttributeView.readAttributes().creationTime().toMillis()));
        return fileContent;
    }catch (IOException e){
        return null;
    }

}
 
Example 19
Source Project: j2cl   Source File: J2clUtils.java    License: Apache License 2.0 5 votes vote down vote up
private static void maybeResetAllTimeStamps(Path path) throws IOException {
  if (!DETERMINISTIC_TIMESTAMPS) {
    return;
  }
  Files.getFileAttributeView(path, BasicFileAttributeView.class)
      .setTimes(FileTime.fromMillis(0), FileTime.fromMillis(0), FileTime.fromMillis(0));
}
 
Example 20
Source Project: openjdk-jdk9   Source File: ZipFSTester.java    License: GNU General Public License v2.0 5 votes vote down vote up
static void testTime(Path src) throws Exception {
    BasicFileAttributes attrs = Files
                    .getFileAttributeView(src, BasicFileAttributeView.class)
                    .readAttributes();
    // create a new filesystem, copy this file into it
    Map<String, Object> env = new HashMap<String, Object>();
    env.put("create", "true");
    Path fsPath = getTempPath();
    FileSystem fs = newZipFileSystem(fsPath, env);

    System.out.println("test copy with timestamps...");
    // copyin
    Path dst = getPathWithParents(fs, "me");
    Files.copy(src, dst, COPY_ATTRIBUTES);
    checkEqual(src, dst);
    System.out.println("mtime: " + attrs.lastModifiedTime());
    System.out.println("ctime: " + attrs.creationTime());
    System.out.println("atime: " + attrs.lastAccessTime());
    System.out.println(" ==============>");
    BasicFileAttributes dstAttrs = Files
                    .getFileAttributeView(dst, BasicFileAttributeView.class)
                    .readAttributes();
    System.out.println("mtime: " + dstAttrs.lastModifiedTime());
    System.out.println("ctime: " + dstAttrs.creationTime());
    System.out.println("atime: " + dstAttrs.lastAccessTime());

    // 1-second granularity
    if (attrs.lastModifiedTime().to(TimeUnit.SECONDS) !=
        dstAttrs.lastModifiedTime().to(TimeUnit.SECONDS) ||
        attrs.lastAccessTime().to(TimeUnit.SECONDS) !=
        dstAttrs.lastAccessTime().to(TimeUnit.SECONDS) ||
        attrs.creationTime().to(TimeUnit.SECONDS) !=
        dstAttrs.creationTime().to(TimeUnit.SECONDS)) {
        throw new RuntimeException("Timestamp Copy Failed!");
    }
    Files.delete(fsPath);
}
 
Example 21
Source Project: mycore   Source File: MCRFileSystemProvider.java    License: GNU General Public License v3.0 5 votes vote down vote up
private static void copyDirectoryAttributes(MCRDirectory source, MCRDirectory target)
    throws IOException {
    Path tgtLocalPath = target.getLocalPath();
    Path srcLocalPath = source.getLocalPath();
    BasicFileAttributes srcAttrs = Files
        .readAttributes(srcLocalPath, BasicFileAttributes.class);
    Files.getFileAttributeView(tgtLocalPath, BasicFileAttributeView.class)
        .setTimes(srcAttrs.lastModifiedTime(), srcAttrs.lastAccessTime(), srcAttrs.creationTime());
}
 
Example 22
Source Project: jimfs   Source File: BasicAttributeProviderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testView() throws IOException {
  BasicFileAttributeView view = provider.view(fileLookup(), NO_INHERITED_VIEWS);

  assertThat(view).isNotNull();
  assertThat(view.name()).isEqualTo("basic");

  BasicFileAttributes attrs = view.readAttributes();
  assertThat(attrs.fileKey()).isEqualTo(0);

  FileTime time = attrs.creationTime();
  assertThat(attrs.lastAccessTime()).isEqualTo(time);
  assertThat(attrs.lastModifiedTime()).isEqualTo(time);

  view.setTimes(null, null, null);

  attrs = view.readAttributes();
  assertThat(attrs.creationTime()).isEqualTo(time);
  assertThat(attrs.lastAccessTime()).isEqualTo(time);
  assertThat(attrs.lastModifiedTime()).isEqualTo(time);

  view.setTimes(FileTime.fromMillis(0L), null, null);

  attrs = view.readAttributes();
  assertThat(attrs.creationTime()).isEqualTo(time);
  assertThat(attrs.lastAccessTime()).isEqualTo(time);
  assertThat(attrs.lastModifiedTime()).isEqualTo(FileTime.fromMillis(0L));
}
 
Example 23
@Override
public void setTimes(FileTime lastModifiedTime, FileTime lastAccessTime, FileTime createTime) throws IOException {
    MCRStoredNode node = resolveNode();
    BasicFileAttributeView localView = Files
        .getFileAttributeView(node.getLocalPath(), BasicFileAttributeView.class);
    localView.setTimes(lastModifiedTime, lastAccessTime, createTime);
}
 
Example 24
Source Project: mycore   Source File: MCRDirectoryStream.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public <V extends FileAttributeView> V getFileAttributeView(Class<V> type) {
    V fileAttributeView = baseStream.getFileAttributeView(type);
    if (fileAttributeView != null) {
        return fileAttributeView;
    }
    if (type == MCRMD5AttributeView.class) {
        BasicFileAttributeView baseView = baseStream.getFileAttributeView(BasicFileAttributeView.class);
        return (V) new MD5FileAttributeViewImpl(baseView, (v) -> dir);
    }
    return null;
}
 
Example 25
Source Project: mycore   Source File: MCRDirectoryStream.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public <V extends FileAttributeView> V getFileAttributeView(Path path, Class<V> type, LinkOption... options) {
    Path localRelativePath = toLocalPath(path);
    if (type == MCRMD5AttributeView.class) {
        BasicFileAttributeView baseView = baseStream.getFileAttributeView(localRelativePath,
            BasicFileAttributeView.class, options);
        return (V) new MD5FileAttributeViewImpl(baseView, (v) -> resolve(path));
    }
    return baseStream.getFileAttributeView(localRelativePath, type, options);
}
 
Example 26
@Override
public void setTimes(FileTime lastModifiedTime, FileTime lastAccessTime, FileTime createTime) throws IOException {
    MCRFilesystemNode node = resolveNode();
    if (node instanceof MCRFile) {
        MCRFile file = (MCRFile) node;
        file.adjustMetadata(lastModifiedTime, file.getMD5(), file.getSize());
        Files.getFileAttributeView(file.getLocalFile().toPath(), BasicFileAttributeView.class).setTimes(
            lastModifiedTime,
            lastAccessTime, createTime);
    } else if (node instanceof MCRDirectory) {
        LOGGER.warn("Setting times on directories is not supported: {}", node.toPath());
    }
}
 
Example 27
Source Project: lucene-solr   Source File: RawLocalFileSystem.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Sets the {@link Path}'s last modified time and last access time to
 * the given valid times.
 *
 * @param mtime the modification time to set (only if no less than zero).
 * @param atime the access time to set (only if no less than zero).
 * @throws IOException if setting the times fails.
 */
@Override
public void setTimes(Path p, long mtime, long atime) throws IOException {
  try {
    BasicFileAttributeView view = Files.getFileAttributeView(
        pathToFile(p).toPath(), BasicFileAttributeView.class);
    FileTime fmtime = (mtime >= 0) ? FileTime.fromMillis(mtime) : null;
    FileTime fatime = (atime >= 0) ? FileTime.fromMillis(atime) : null;
    view.setTimes(fmtime, fatime, null);
  } catch (NoSuchFileException e) {
    throw new FileNotFoundException("File " + p + " does not exist");
  }
}
 
Example 28
Source Project: sftp-fs   Source File: SFTPFileSystemProvider.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns a file attribute view of a given type.
 * This method works in exactly the manner specified by the {@link Files#getFileAttributeView(Path, Class, LinkOption...)} method.
 * <p>
 * This provider supports {@link BasicFileAttributeView}, {@link FileOwnerAttributeView} and {@link PosixFileAttributeView}.
 * All other classes will result in a {@code null} return value.
 * <p>
 * Note: if the type is {@link BasicFileAttributeView} or a sub type, the last access time and creation time must be {@code null} when calling
 * {@link BasicFileAttributeView#setTimes(FileTime, FileTime, FileTime)}, otherwise an exception will be thrown.
 * When setting the owner or group for the path, the name must be the UID/GID of the owner/group.
 */
@Override
public <V extends FileAttributeView> V getFileAttributeView(Path path, Class<V> type, LinkOption... options) {
    Objects.requireNonNull(type);
    if (type == BasicFileAttributeView.class) {
        return type.cast(new AttributeView("basic", toSFTPPath(path))); //$NON-NLS-1$
    }
    if (type == FileOwnerAttributeView.class) {
        return type.cast(new AttributeView("owner", toSFTPPath(path))); //$NON-NLS-1$
    }
    if (type == PosixFileAttributeView.class) {
        return type.cast(new AttributeView("posix", toSFTPPath(path))); //$NON-NLS-1$
    }
    return null;
}
 
Example 29
Source Project: sftp-fs   Source File: SFTPFileSystemProviderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetFileAttributeViewReadAttributes() throws IOException {
    addDirectory("/foo/bar");

    SFTPFileSystemProvider provider = new SFTPFileSystemProvider();
    try (SFTPFileSystem fs = newFileSystem(provider, createEnv())) {
        SFTPPath path = new SFTPPath(fs, "/foo/bar");

        BasicFileAttributeView view = fs.provider().getFileAttributeView(path, BasicFileAttributeView.class);
        assertNotNull(view);

        BasicFileAttributes attributes = view.readAttributes();
        assertTrue(attributes.isDirectory());
    }
}
 
Example 30
@Test
public void creationTime() throws Exception {
	Path root = fs.getRootDirectories().iterator().next();

	Path folder = root.resolve("folder");
	Files.createDirectory(folder);

	Path file = root.resolve("file");
	Files.createFile(file);

	int manyDays = 365 * 12;
	FileTime someTimeAgo = FileTime.from(manyDays, TimeUnit.DAYS);

	Files.getFileAttributeView(folder, BasicFileAttributeView.class)
			.setTimes(null, null, someTimeAgo);
	Files.getFileAttributeView(file, BasicFileAttributeView.class)
			.setTimes(null, null, someTimeAgo);
	Files.getFileAttributeView(root, BasicFileAttributeView.class)
			.setTimes(null, null, someTimeAgo);

	// Should be equal, +/- 2 seconds
	assertEquals((double) someTimeAgo.toMillis(),
			(double) ((FileTime) Files.getAttribute(file, "creationTime"))
					.toMillis(), 2001);
	assertEquals(
			(double) someTimeAgo.toMillis(),
			(double) ((FileTime) Files.getAttribute(folder, "creationTime"))
					.toMillis(), 2001);

	// FIXME: FAils with NullPointerException! :(
	// assertEquals((double)someTimeAgo.toMillis(), (double)
	// ((FileTime)Files.getAttribute(root, "creationTime")).toMillis(),
	// 2001);

}