java.nio.file.attribute.BasicFileAttributeView#setTimes ( )源码实例Demo

下面列出了java.nio.file.attribute.BasicFileAttributeView#setTimes ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc)
		throws IOException {
	try {
		if (copyOptionsSet.contains(COPY_ATTRIBUTES)) {
			/*
			 * Copy file times. Inspired by
			 * java.nio.file.CopyMoveHelper.copyToForeignTarget()
			 */
			BasicFileAttributes attrs = readAttributes(dir,
					BasicFileAttributes.class, linkOptions);
			BasicFileAttributeView view = getFileAttributeView(
					toDestination(dir), BasicFileAttributeView.class,
					linkOptions);
			view.setTimes(attrs.lastModifiedTime(), attrs.lastAccessTime(),
					attrs.creationTime());
		}
		return CONTINUE;
	} catch (IOException ex) {
		return visitFileFailed(dir, ex);
	}
}
 
源代码2 项目: n4js   文件: CommandRebuildTest.java
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());
}
 
源代码3 项目: mycore   文件: MCRFileSystemProvider.java
private static void copyFileAttributes(MCRFile source, MCRFile target)
    throws IOException {
    Path targetLocalFile = target.getLocalPath();
    BasicFileAttributeView targetBasicFileAttributeView = Files.getFileAttributeView(targetLocalFile,
        BasicFileAttributeView.class);
    BasicFileAttributes srcAttr = Files.readAttributes(source.getLocalPath(), BasicFileAttributes.class);
    target.setMD5(source.getMD5());
    targetBasicFileAttributeView.setTimes(srcAttr.lastModifiedTime(), srcAttr.lastAccessTime(),
        srcAttr.creationTime());
}
 
源代码4 项目: mycore   文件: MCRBasicFileAttributeViewImpl.java
@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);
}
 
源代码5 项目: lucene-solr   文件: RawLocalFileSystem.java
/**
 * 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");
  }
}
 
源代码6 项目: FastCopy   文件: FileUtils.java
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);
		}
	}

}
 
源代码7 项目: jimfs   文件: BasicAttributeProviderTest.java
@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));
}
 
@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));
    }
}
 
源代码9 项目: openjdk-jdk9   文件: UnixSocketFile.java
public static void main(String[] args)
    throws InterruptedException, IOException {

    // Use 'which' to verify that 'nc' is available and skip the test
    // if it is not.
    Process proc = Runtime.getRuntime().exec("which nc");
    InputStream stdout = proc.getInputStream();
    int b = stdout.read();
    proc.destroy();
    if (b == -1) {
        System.err.println("Netcat command unavailable; skipping test.");
        return;
    }

    // Create a new sub-directory of the nominal test directory in which
    // 'nc' will create the socket file.
    String testSubDir = System.getProperty("test.dir", ".")
        + File.separator + TEST_SUB_DIR;
    Path socketTestDir = Paths.get(testSubDir);
    Files.createDirectory(socketTestDir);

    // Set the path of the socket file.
    String socketFilePath = testSubDir + File.separator
        + SOCKET_FILE_NAME;

    // Create a process which executes the nc (netcat) utility to create
    // a socket file at the indicated location.
    FileSystem fs = FileSystems.getDefault();
    try (WatchService ws = fs.newWatchService()) {
        // Watch the test sub-directory to receive notification when an
        // entry, i.e., the socket file, is added to the sub-directory.
        WatchKey wk = socketTestDir.register(ws,
                StandardWatchEventKinds.ENTRY_CREATE);

        // Execute the 'nc' command.
        proc = Runtime.getRuntime().exec(CMD_BASE + " " + socketFilePath);

        // Wait until the socket file is created.
        WatchKey key = ws.take();
        if (key != wk) {
            throw new RuntimeException("Unknown entry created - expected: "
                + wk.watchable() + ", actual: " + key.watchable());
        }
        wk.cancel();
    }

    // Verify that the socket file in fact exists.
    Path socketPath = fs.getPath(socketFilePath);
    if (!Files.exists(socketPath)) {
        throw new RuntimeException("Socket file " + socketFilePath
            + " was not created by \"nc\" command.");
    }

    // Retrieve the most recent access and modification times of the
    // socket file; print the values.
    BasicFileAttributeView attributeView = Files.getFileAttributeView(
            socketPath, BasicFileAttributeView.class);
    BasicFileAttributes oldAttributes = attributeView.readAttributes();
    FileTime oldAccessTime = oldAttributes.lastAccessTime();
    FileTime oldModifiedTime = oldAttributes.lastModifiedTime();
    System.out.println("Old times: " + oldAccessTime
        + " " + oldModifiedTime);

    // Calculate the time to which the access and modification times of the
    // socket file will be changed.
    FileTime newFileTime =
        FileTime.fromMillis(oldAccessTime.toMillis() + 1066);

    try {
        // Set the access and modification times of the socket file.
        attributeView.setTimes(newFileTime, newFileTime, null);

        // Retrieve the updated access and modification times of the
        // socket file; print the values.
        FileTime newAccessTime = null;
        FileTime newModifiedTime = null;
        BasicFileAttributes newAttributes = attributeView.readAttributes();
        newAccessTime = newAttributes.lastAccessTime();
        newModifiedTime = newAttributes.lastModifiedTime();
        System.out.println("New times: " + newAccessTime + " "
            + newModifiedTime);

        // Verify that the updated times have the expected values.
        if ((newAccessTime != null && !newAccessTime.equals(newFileTime))
            || (newModifiedTime != null
                && !newModifiedTime.equals(newFileTime))) {
            throw new RuntimeException("Failed to set correct times.");
        }
    } finally {
        // Destry the process running netcat and delete the socket file.
        proc.destroy();
        Files.delete(socketPath);
    }
}