java.nio.file.Path类的使用及代码示例

x33g5p2x  于2022-01-25 转载在 其他  
字(9.4k)|赞(0)|评价(0)|浏览(305)

本文整理了Java中java.nio.file.Path类的一些代码示例,展示了Path类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Path类的具体详情如下:
包路径:java.nio.file.Path
类名称:Path

Path介绍

暂无

代码示例

canonical example by Tabnine

public void pathUsage() {
  Path currentDir = Paths.get("."); // currentDir = "."
  Path fullPath = currentDir.toAbsolutePath(); // fullPath = "/Users/guest/workspace"
  Path one = currentDir.resolve("file.txt"); // one = "./file.txt"
  Path fileName = one.getFileName(); // fileName = "file.txt"
}

代码示例来源:origin: twosigma/beakerx

private Map<Path, String> getPaths(String pathWithWildcard) {
 String pathWithoutWildcards = pathWithWildcard.replace("*", "");
 try {
  return Files.list(Paths.get(pathWithoutWildcards))
      .filter(path -> path.toString().toLowerCase().endsWith(".jar"))
      .collect(Collectors.toMap(p -> p, o -> o.getFileName().toString()));
 } catch (IOException e) {
  throw new IllegalStateException("Cannot create any jars files in selected path");
 }
}

代码示例来源:origin: neo4j/neo4j

@Override
public File[] listFiles( File directory, final FilenameFilter filter )
{
  try ( Stream<Path> listing = Files.list( path( directory ) ) )
  {
    return listing
        .filter( entry -> filter.accept( entry.getParent().toFile(), entry.getFileName().toString() ) )
        .map( Path::toFile )
        .toArray( File[]::new );
  }
  catch ( IOException e )
  {
    return null;
  }
}

代码示例来源:origin: twosigma/beakerx

private String getSparkexJar() {
  try {
   Path path = Paths.get(EnableSparkSupportMagicCommand.class.getProtectionDomain().getCodeSource().getLocation().toURI());
   return path.getParent().getParent().getParent().resolve("sparkex").resolve("lib").resolve("sparkex.jar").toString();
  } catch (Exception e) {
   throw new RuntimeException(e);
  }
 }
}

代码示例来源:origin: spring-projects/spring-framework

/**
 * This implementation returns the name of the file.
 * @see java.nio.file.Path#getFileName()
 */
@Override
public String getFilename() {
  return this.path.getFileName().toString();
}

代码示例来源:origin: spring-projects/spring-framework

@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
  Files.createDirectories(dest.resolve(src.relativize(dir)));
  return FileVisitResult.CONTINUE;
}
@Override

代码示例来源:origin: spring-projects/spring-framework

@Override
  public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
    Files.copy(file, dest.resolve(src.relativize(file)), StandardCopyOption.REPLACE_EXISTING);
    return FileVisitResult.CONTINUE;
  }
});

代码示例来源:origin: apache/flink

@Test
public void testStopJobAfterSavepoint() throws Exception {
  setUpWithCheckpointInterval(10L);
  final String savepointLocation = cancelWithSavepoint();
  final JobStatus jobStatus = clusterClient.getJobStatus(jobGraph.getJobID()).get();
  assertThat(jobStatus, isOneOf(JobStatus.CANCELED, JobStatus.CANCELLING));
  final List<Path> savepoints;
  try (Stream<Path> savepointFiles = Files.list(savepointDirectory)) {
    savepoints = savepointFiles.map(Path::getFileName).collect(Collectors.toList());
  }
  assertThat(savepoints, hasItem(Paths.get(savepointLocation).getFileName()));
}

代码示例来源:origin: twosigma/beakerx

private List<String> mavenBuildClasspath() {
 String jarPathsAsString = null;
 try {
  File fileToClasspath = new File(pathToMavenRepo, MAVEN_BUILT_CLASSPATH_FILE_NAME);
  InputStream fileInputStream = new FileInputStream(fileToClasspath);
  jarPathsAsString = IOUtils.toString(fileInputStream, StandardCharsets.UTF_8);
 } catch (IOException e) {
  throw new RuntimeException(e);
 }
 Stream<String> stream = Arrays.stream(jarPathsAsString.split(File.pathSeparator));
 return stream.map(x -> Paths.get(x).getFileName().toString()).collect(Collectors.toList());
}

代码示例来源:origin: apache/storm

static Collection<String> getLocalizedUsers(Path localBaseDir) throws IOException {
  Path userCacheDir = getUserCacheDir(localBaseDir);
  if (!Files.exists(userCacheDir)) {
    return Collections.emptyList();
  }
  return Files.list(userCacheDir).map((p) -> p.getFileName().toString()).collect(Collectors.toList());
}

代码示例来源:origin: apache/flink

public void appendConfiguration(Configuration config) throws IOException {
  final Configuration mergedConfig = new Configuration();
  mergedConfig.addAll(defaultConfig);
  mergedConfig.addAll(config);
  final List<String> configurationLines = mergedConfig.toMap().entrySet().stream()
    .map(entry -> entry.getKey() + ": " + entry.getValue())
    .collect(Collectors.toList());
  Files.write(conf.resolve("flink-conf.yaml"), configurationLines);
}

代码示例来源:origin: linlinjava/litemall

@Override
public Stream<Path> loadAll() {
  try {
    return Files.walk(rootLocation, 1)
        .filter(path -> !path.equals(rootLocation))
        .map(path -> rootLocation.relativize(path));
  } catch (IOException e) {
    throw new RuntimeException("Failed to read stored files", e);
  }
}

代码示例来源:origin: neo4j/neo4j

private Map<Path, Description> describeRecursively( Path directory ) throws IOException
{
  return Files.walk( directory )
      .map( path -> pair( directory.relativize( path ), describe( path ) ) )
      .collect( HashMap::new,
          ( pathDescriptionHashMap, pathDescriptionPair ) ->
              pathDescriptionHashMap.put( pathDescriptionPair.first(), pathDescriptionPair.other() ),
          HashMap::putAll );
}

代码示例来源:origin: prestodb/presto

@Test
public void testCreateWithNonexistentStagingDirectory()
    throws Exception
{
  java.nio.file.Path stagingParent = createTempDirectory("test");
  java.nio.file.Path staging = Paths.get(stagingParent.toString(), "staging");
  // stagingParent = /tmp/testXXX
  // staging = /tmp/testXXX/staging
  try (PrestoS3FileSystem fs = new PrestoS3FileSystem()) {
    MockAmazonS3 s3 = new MockAmazonS3();
    Configuration conf = new Configuration();
    conf.set(S3_STAGING_DIRECTORY, staging.toString());
    fs.initialize(new URI("s3n://test-bucket/"), conf);
    fs.setS3Client(s3);
    FSDataOutputStream stream = fs.create(new Path("s3n://test-bucket/test"));
    stream.close();
    assertTrue(Files.exists(staging));
  }
  finally {
    deleteRecursively(stagingParent, ALLOW_INSECURE);
  }
}

代码示例来源:origin: sleekbyte/tailor

@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException {
  Path relative = Paths.get(base.relativize(file.toUri()).getPath());
  if (excludeMatcher.stream().anyMatch(pathMatcher -> pathMatcher.matches(relative))) {
    return FileVisitResult.CONTINUE;
  }
  if ((isParentIncluded.getOrDefault(file.getParent(), false)
    || includeMatcher.stream().anyMatch(pathMatcher -> pathMatcher.matches(relative)))
    && (file.toFile().getCanonicalPath().endsWith(".swift") && file.toFile().canRead())) {
    fileNames.add(file.toFile().getCanonicalPath());
  }
  return FileVisitResult.CONTINUE;
}

代码示例来源:origin: apache/flink

private static Optional<Path> findExternalizedCheckpoint(File checkpointDir, JobID jobId) throws IOException {
  try (Stream<Path> checkpoints = Files.list(checkpointDir.toPath().resolve(jobId.toString()))) {
    return checkpoints
      .filter(path -> path.getFileName().toString().startsWith("chk-"))
      .filter(path -> {
        try (Stream<Path> checkpointFiles = Files.list(path)) {
          return checkpointFiles.anyMatch(child -> child.getFileName().toString().contains("meta"));
        } catch (IOException ignored) {
          return false;
        }
      })
      .findAny();
  }
}

代码示例来源:origin: neo4j/neo4j

@Test
public void shouldThrowWhenRelativePathIsOutsideImportDirectory() throws Exception
{
  assumeFalse( Paths.get( "/" ).relativize( Paths.get( "/../baz.csv" ) ).toString().equals( "baz.csv" ) );
  File importDir = new File( "/tmp/neo4jtest" ).getAbsoluteFile();
  final Config config = Config.defaults( GraphDatabaseSettings.load_csv_file_url_root, importDir.toString() );
  try
  {
    URLAccessRules.fileAccess().validate( config, new URL( "file:///../baz.csv" ) );
    fail( "expected exception not thrown " );
  }
  catch ( URLAccessValidationError error )
  {
    assertThat( error.getMessage(), equalTo( "file URL points outside configured import directory" ) );
  }
}

代码示例来源:origin: google/error-prone

private DescriptionBasedDiff(
  JCCompilationUnit compilationUnit,
  boolean ignoreOverlappingFixes,
  ImportOrganizer importOrganizer) {
 this.compilationUnit = checkNotNull(compilationUnit);
 URI sourceFileUri = compilationUnit.getSourceFile().toUri();
 this.sourcePath =
   (sourceFileUri.isAbsolute() && Objects.equals(sourceFileUri.getScheme(), "file"))
     ? Paths.get(sourceFileUri).toAbsolutePath().toString()
     : sourceFileUri.getPath();
 this.ignoreOverlappingFixes = ignoreOverlappingFixes;
 this.importsToAdd = new LinkedHashSet<>();
 this.importsToRemove = new LinkedHashSet<>();
 this.endPositions = compilationUnit.endPositions;
 this.importOrganizer = importOrganizer;
}

代码示例来源:origin: prestodb/presto

public void generate()
    throws Exception
{
  initPlanTest();
  try {
    getQueryResourcePaths()
        .parallel()
        .forEach(queryResourcePath -> {
          try {
            Path queryPlanWritePath = Paths.get(
                getSourcePath().toString(),
                "src/test/resources",
                getQueryPlanResourcePath(queryResourcePath));
            createParentDirs(queryPlanWritePath.toFile());
            write(generateQueryPlan(read(queryResourcePath)).getBytes(UTF_8), queryPlanWritePath.toFile());
            System.out.println("Generated expected plan for query: " + queryResourcePath);
          }
          catch (IOException e) {
            throw new UncheckedIOException(e);
          }
        });
  }
  finally {
    destroyPlanTest();
  }
}

代码示例来源:origin: Swagger2Markup/swagger2markup

@Test
public void testFromHttpURI() throws IOException, URISyntaxException {
  //Given
  Path outputDirectory = Paths.get("build/test/asciidoc/fromUri");
  FileUtils.deleteQuietly(outputDirectory.toFile());
  //When
  Swagger2MarkupConverter.from(URI.create("http://petstore.swagger.io/v2/swagger.json")).build()
      .toFolder(outputDirectory);
  //Then
  String[] files = outputDirectory.toFile().list();
  assertThat(files).hasSize(4).containsAll(expectedFiles);
}

相关文章