Java Code Examples for java.nio.file.Files#createLink()

The following examples show how to use java.nio.file.Files#createLink() . 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: SyncClient.java    From incubator-iotdb with Apache License 2.0 6 votes vote down vote up
/**
 * Make snapshot<hard link> for new tsfile and its .restore file.
 *
 * @param file new tsfile to be synced
 */
File makeFileSnapshot(File file) throws IOException {
  File snapshotFile = SyncUtils.getSnapshotFile(file);
  if (!snapshotFile.getParentFile().exists()) {
    snapshotFile.getParentFile().mkdirs();
  }
  Path link = FileSystems.getDefault().getPath(snapshotFile.getAbsolutePath());
  Path target = FileSystems.getDefault().getPath(file.getAbsolutePath());
  Files.createLink(link, target);
  link = FileSystems.getDefault()
      .getPath(snapshotFile.getAbsolutePath() + TsFileResource.RESOURCE_SUFFIX);
  target = FileSystems.getDefault()
      .getPath(file.getAbsolutePath() + TsFileResource.RESOURCE_SUFFIX);
  Files.createLink(link, target);
  return snapshotFile;
}
 
Example 2
Source File: JimfsUnixLikeFileSystemTest.java    From jimfs with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateLink_relative() throws IOException {
  Files.createFile(path("test.txt"));
  Files.createLink(path("link.txt"), path("test.txt"));

  // don't assert that the link is the same file here, just that it was created
  // later tests check that linking works correctly
  assertThatPath("/work/link.txt", NOFOLLOW_LINKS).isRegularFile();
  assertThatPath("link.txt", NOFOLLOW_LINKS).isRegularFile();
  assertThatPath("/work").hasChildren("link.txt", "test.txt");

  Files.createDirectory(path("foo"));
  Files.createLink(path("foo/link.txt"), path("test.txt"));

  assertThatPath("/work/foo/link.txt", NOFOLLOW_LINKS).isRegularFile();
  assertThatPath("foo/link.txt", NOFOLLOW_LINKS).isRegularFile();
  assertThatPath("foo").hasChildren("link.txt");
}
 
Example 3
Source File: JimfsUnixLikeFileSystemTest.java    From jimfs with Apache License 2.0 6 votes vote down vote up
@Test
public void testLink_forSymbolicLink_usesSymbolicLinkTarget() throws IOException {
  Files.createFile(path("/file"));
  Files.createSymbolicLink(path("/symlink"), path("/file"));

  Object key = getFileKey("/file");

  Files.createLink(path("/link"), path("/symlink"));

  assertThatPath("/link")
      .isRegularFile()
      .and()
      .hasLinkCount(2)
      .and()
      .attribute("fileKey")
      .is(key);
}
 
Example 4
Source File: FileUtils.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
public static void createHardLink(File from, File to)
{
    if (to.exists())
        throw new RuntimeException("Tried to create duplicate hard link to " + to);
    if (!from.exists())
        throw new RuntimeException("Tried to hard link to file that does not exist " + from);

    try
    {
        Files.createLink(to.toPath(), from.toPath());
    }
    catch (IOException e)
    {
        throw new FSWriteError(e, to);
    }
}
 
Example 5
Source File: RocksDBIncrementalRestoreOperation.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
/**
 * This recreates the new working directory of the recovered RocksDB instance and links/copies the contents from
 * a local state.
 */
private void restoreInstanceDirectoryFromPath(Path source, String instanceRocksDBPath) throws IOException {

	FileSystem fileSystem = source.getFileSystem();

	final FileStatus[] fileStatuses = fileSystem.listStatus(source);

	if (fileStatuses == null) {
		throw new IOException("Cannot list file statues. Directory " + source + " does not exist.");
	}

	for (FileStatus fileStatus : fileStatuses) {
		final Path filePath = fileStatus.getPath();
		final String fileName = filePath.getName();
		File restoreFile = new File(source.getPath(), fileName);
		File targetFile = new File(instanceRocksDBPath, fileName);
		if (fileName.endsWith(SST_FILE_SUFFIX)) {
			// hardlink'ing the immutable sst-files.
			Files.createLink(targetFile.toPath(), restoreFile.toPath());
		} else {
			// true copy for all other files.
			Files.copy(restoreFile.toPath(), targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
		}
	}
}
 
Example 6
Source File: SimpleFileOperations.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void hardLink(final Path source, final Path newLink) throws IOException {
  DirectoryHelper.mkdir(newLink.getParent());
  try {
    Files.createLink(newLink, source);
  }
  catch (UnsupportedOperationException e) {
    // In some situations, an unsupported file link actually throws FileSystemException rather than
    // UnsupportedException, so wrap USEs here to narrow the range of exceptions that need catching.
    throw new IOException(e);
  }
  log.debug("Hard link created from {} to {}", newLink, source);
}
 
Example 7
Source File: JimfsUnixLikeFileSystemTest.java    From jimfs with Apache License 2.0 5 votes vote down vote up
@Test
public void testLink_failsForNonRegularFile() throws IOException {
  Files.createDirectory(path("/dir"));

  try {
    Files.createLink(path("/link"), path("/dir"));
    fail();
  } catch (FileSystemException expected) {
    assertEquals("/link", expected.getFile());
    assertEquals("/dir", expected.getOtherFile());
  }

  assertThatPath("/link").doesNotExist();
}
 
Example 8
Source File: JimfsUnixLikeFileSystemTest.java    From jimfs with Apache License 2.0 5 votes vote down vote up
@Test
public void testLink() throws IOException {
  Files.createFile(path("/file.txt"));
  // checking link count requires "unix" attribute support, which we're using here
  assertThatPath("/file.txt").hasLinkCount(1);

  Files.createLink(path("/link.txt"), path("/file.txt"));

  assertThatPath("/link.txt").isSameFileAs("/file.txt");

  assertThatPath("/file.txt").hasLinkCount(2);
  assertThatPath("/link.txt").hasLinkCount(2);

  assertThatPath("/file.txt").containsNoBytes();
  assertThatPath("/link.txt").containsNoBytes();

  byte[] bytes = {0, 1, 2, 3};
  Files.write(path("/file.txt"), bytes);

  assertThatPath("/file.txt").containsBytes(bytes);
  assertThatPath("/link.txt").containsBytes(bytes);

  Files.write(path("/link.txt"), bytes, APPEND);

  assertThatPath("/file.txt").containsBytes(0, 1, 2, 3, 0, 1, 2, 3);
  assertThatPath("/link.txt").containsBytes(0, 1, 2, 3, 0, 1, 2, 3);

  Files.delete(path("/file.txt"));
  assertThatPath("/link.txt").hasLinkCount(1);

  assertThatPath("/link.txt").containsBytes(0, 1, 2, 3, 0, 1, 2, 3);
}
 
Example 9
Source File: JavaIoFileSystem.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Override
protected void createFSDependentHardLink(Path linkPath, Path originalPath)
    throws IOException {
  Files.createLink(
      java.nio.file.Paths.get(linkPath.toString()),
      java.nio.file.Paths.get(originalPath.toString()));
}
 
Example 10
Source File: IOUtilsTest.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
@Test
public void fileKeysVerifySameFile() throws IOException {
  Path path = root.resolve("a");
  ByteString blob = ByteString.copyFromUtf8("content for a");
  Files.write(path, blob.toByteArray());
  Files.createLink(root.resolve("b"), path);

  List<NamedFileKey> files = IOUtils.listDirentSorted(root, fileStore);
  assertThat(files.size()).isEqualTo(2);
  Object firstKey = files.get(0).fileKey();
  Object secondKey = files.get(1).fileKey();
  assertThat(firstKey).isEqualTo(secondKey);
}
 
Example 11
Source File: EncryptedFileSystemProvider.java    From encfs4j with Apache License 2.0 4 votes vote down vote up
@Override
public void createLink(Path link, Path existing) throws IOException {
	Files.createLink(EncryptedFileSystem.dismantle(link),
			EncryptedFileSystem.dismantle(existing));
}
 
Example 12
Source File: FaultyFileSystem.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void createLink(Path link, Path existing) throws IOException {
    triggerEx(existing, "createLink");
    Files.createLink(unwrap(link), unwrap(existing));
}
 
Example 13
Source File: FaultyFileSystem.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void createLink(Path link, Path existing) throws IOException {
    triggerEx(existing, "createLink");
    Files.createLink(unwrap(link), unwrap(existing));
}
 
Example 14
Source File: FaultyFileSystem.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void createLink(Path link, Path existing) throws IOException {
    triggerEx(existing, "createLink");
    Files.createLink(unwrap(link), unwrap(existing));
}
 
Example 15
Source File: FaultyFileSystem.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void createLink(Path link, Path existing) throws IOException {
    triggerEx(existing, "createLink");
    Files.createLink(unwrap(link), unwrap(existing));
}
 
Example 16
Source File: FaultyFileSystem.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void createLink(Path link, Path existing) throws IOException {
    triggerEx(existing, "createLink");
    Files.createLink(unwrap(link), unwrap(existing));
}
 
Example 17
Source File: FaultyFileSystem.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void createLink(Path link, Path existing) throws IOException {
    triggerEx(existing, "createLink");
    Files.createLink(unwrap(link), unwrap(existing));
}
 
Example 18
Source File: FaultyFileSystem.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void createLink(Path link, Path existing) throws IOException {
    triggerEx(existing, "createLink");
    Files.createLink(unwrap(link), unwrap(existing));
}
 
Example 19
Source File: BuildCommand.java    From buck with Apache License 2.0 4 votes vote down vote up
private void linkRuleToHashedBuckOut(
    BuildRule rule,
    SourcePathResolverAdapter pathResolver,
    boolean buckOutCompatLink,
    OutputLabel outputLabel,
    HashedBuckOutLinkMode linkMode)
    throws IOException {
  Optional<Path> outputPath =
      PathUtils.getUserFacingOutputPath(
          pathResolver, rule, buckOutCompatLink, outputLabel, showOutputs);
  if (!outputPath.isPresent()) {
    return;
  }
  Path absolutePathWithHash = outputPath.get().toAbsolutePath();
  Optional<Path> maybeAbsolutePathWithoutHash =
      BuildPaths.removeHashFrom(absolutePathWithHash, rule.getBuildTarget());
  if (!maybeAbsolutePathWithoutHash.isPresent()) {
    // hash was not found, for example `export_file` rule outputs files in source directory, not
    // in buck-out
    // so we don't create any links
    return;
  }
  Path absolutePathWithoutHash = maybeAbsolutePathWithoutHash.get();
  MostFiles.deleteRecursivelyIfExists(absolutePathWithoutHash);
  Files.createDirectories(absolutePathWithoutHash.getParent());

  switch (linkMode) {
    case SYMLINK:
      Files.createSymbolicLink(absolutePathWithoutHash, absolutePathWithHash);
      break;
    case HARDLINK:
      boolean isDirectory;
      try {
        isDirectory =
            Files.readAttributes(absolutePathWithHash, BasicFileAttributes.class).isDirectory();
      } catch (NoSuchFileException e) {
        // Rule did not produce a file.
        // It should not be possible, but it happens.
        return;
      }
      if (isDirectory) {
        Files.createSymbolicLink(absolutePathWithoutHash, absolutePathWithHash);
      } else {
        Files.createLink(absolutePathWithoutHash, absolutePathWithHash);
      }
      break;
    case NONE:
      break;
  }
}
 
Example 20
Source File: NNUpgradeUtil.java    From big-c with Apache License 2.0 3 votes vote down vote up
/**
 * Perform any steps that must succeed across all storage dirs/JournalManagers
 * involved in an upgrade before proceeding onto the actual upgrade stage. If
 * a call to any JM's or local storage dir's doPreUpgrade method fails, then
 * doUpgrade will not be called for any JM. The existing current dir is
 * renamed to previous.tmp, and then a new, empty current dir is created.
 *
 * @param conf configuration for creating {@link EditLogFileOutputStream}
 * @param sd the storage directory to perform the pre-upgrade procedure.
 * @throws IOException in the event of error
 */
static void doPreUpgrade(Configuration conf, StorageDirectory sd)
    throws IOException {
  LOG.info("Starting upgrade of storage directory " + sd.getRoot());

  // rename current to tmp
  renameCurToTmp(sd);

  final File curDir = sd.getCurrentDir();
  final File tmpDir = sd.getPreviousTmp();
  List<String> fileNameList = IOUtils.listDirectory(tmpDir, new FilenameFilter() {
    @Override
    public boolean accept(File dir, String name) {
      return dir.equals(tmpDir)
          && name.startsWith(NNStorage.NameNodeFile.EDITS.getName());
    }
  });

  for (String s : fileNameList) {
    File prevFile = new File(tmpDir, s);
    File newFile = new File(curDir, prevFile.getName());
    Files.createLink(newFile.toPath(), prevFile.toPath());
  }
}