java.nio.file.attribute.BasicFileAttributeView Java Examples

The following examples show how to use java.nio.file.attribute.BasicFileAttributeView. 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 File: HaloUtils.java    From stone with 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 #2
Source File: LocalIgfsSecondaryFileSystem.java    From ignite with 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 #3
Source File: LocalFileSystemUtils.java    From ignite with 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 #4
Source File: FileUtil.java    From xnx3 with 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 #5
Source File: MCRDirectoryStream.java    From mycore with 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 #6
Source File: AttributeServiceTest.java    From jimfs with 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 #7
Source File: PathUtil.java    From wildfly-core with 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 #8
Source File: MCRFileSystemProvider.java    From mycore with 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 #9
Source File: TestFiles.java    From jsr203-hadoop with 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 #10
Source File: TestFileStore.java    From jsr203-hadoop with 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 #11
Source File: HaloUtils.java    From blog-sharon with 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 #12
Source File: TestFileStore.java    From jsr203-hadoop with 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 #13
Source File: SensUtils.java    From SENS with 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 #14
Source File: TestBundleFileSystem.java    From incubator-taverna-language with Apache License 2.0 5 votes vote down vote up
@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);

}
 
Example #15
Source File: MCRDirectoryStream.java    From mycore with 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 #16
Source File: OnStartupTriggeringPolicyTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testPolicy() throws Exception {
    //System.setProperty("log4j2.debug", "true");
    //System.setProperty("log4j2.StatusLogger.level", "trace");
    final Configuration configuration = new DefaultConfiguration();
    final Path target = Paths.get(TARGET_FILE);
    target.toFile().getParentFile().mkdirs();
    final long timeStamp = System.currentTimeMillis() - (1000 * 60 * 60 * 24);
    final String expectedDate = formatter.format(timeStamp);
    final String rolledFileName = ROLLED_FILE_PREFIX + expectedDate + ROLLED_FILE_SUFFIX;
    final Path rolled = Paths.get(rolledFileName);
    final long copied;
    try (final InputStream is = new ByteArrayInputStream(TEST_DATA.getBytes("UTF-8"))) {
        copied = Files.copy(is, target, StandardCopyOption.REPLACE_EXISTING);
    }
    final long size = Files.size(target);
    assertTrue(size > 0);
    assertEquals(copied, size);

    final FileTime fileTime = FileTime.fromMillis(timeStamp);
    final BasicFileAttributeView attrs = Files.getFileAttributeView(target, BasicFileAttributeView.class);
    attrs.setTimes(fileTime, fileTime, fileTime);
    final PatternLayout layout = PatternLayout.newBuilder().setPattern("%msg").setConfiguration(configuration)
            .build();
    final RolloverStrategy strategy = DefaultRolloverStrategy.newBuilder().setCompressionLevelStr("0")
            .setStopCustomActionsOnError(true).setConfig(configuration).build();
    final OnStartupTriggeringPolicy policy = OnStartupTriggeringPolicy.createPolicy(1);
    try (final RollingFileManager manager = RollingFileManager.getFileManager(TARGET_FILE, TARGET_PATTERN, true,
            false, policy, strategy, null, layout, 8192, true, false, null, null, null, configuration)) {
        manager.initialize();
        final String files = Arrays.toString(new File(TARGET_FOLDER).listFiles());
        assertTrue(target.toString() + ", files = " + files, Files.exists(target));
        assertEquals(target.toString(), 0, Files.size(target));
        assertTrue("Missing: " + rolled.toString() + ", files on disk = " + files, Files.exists(rolled));
        assertEquals(rolled.toString(), size, Files.size(rolled));
    }
}
 
Example #17
Source File: ZipFSTester.java    From openjdk-jdk9 with 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 #18
Source File: EnumFiles.java    From MonitorClient with 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 File: CommandRebuildTest.java    From n4js with 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 #20
Source File: HadoopFileStore.java    From jsr203-hadoop with Apache License 2.0 5 votes vote down vote up
@Override
public boolean supportsFileAttributeView(
    Class<? extends FileAttributeView> type) {
  if (type == BasicFileAttributeView.class) {
    return this.system.supportedFileAttributeViews().contains("basic");
  }
  if (type == PosixFileAttributeView.class) {
    return this.system.supportedFileAttributeViews().contains("posix");
  }
  // FIXME Implements all FileAttributeView checks
  return false;
}
 
Example #21
Source File: JimfsUnixLikeFileSystemTest.java    From jimfs with 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 #22
Source File: MCRFileSystemProvider.java    From mycore with 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 #23
Source File: BasicAttributeProviderTest.java    From jimfs with 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 #24
Source File: MCRBasicFileAttributeViewImpl.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@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 #25
Source File: MCRDirectoryStream.java    From mycore with 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 #26
Source File: FileUtils.java    From FastCopy with Apache License 2.0 5 votes vote down vote up
public  void setFileLastModified(String targetFile, long millis)  {
	if (RunTimeProperties.instance.isKeepOriginalFileDates()) {
		Path tPath = Paths.get(targetFile);
		BasicFileAttributeView attributes = Files.getFileAttributeView(tPath, BasicFileAttributeView.class);
		FileTime time = FileTime.fromMillis(millis);
		try {
			attributes.setTimes(time, time, null);
		} catch (IOException e) {
			rdProUI.print(LogLevel.debug, "Failed to set last modified timestamp for " + targetFile);
		}
	}

}
 
Example #27
Source File: MCRBasicFileAttributeViewImpl.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@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 #28
Source File: RawLocalFileSystem.java    From lucene-solr with 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 #29
Source File: SFTPFileSystemProvider.java    From sftp-fs with 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 #30
Source File: SFTPFileSystemProviderTest.java    From sftp-fs with 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());
    }
}