Tabnine Logo
Path
Code IndexAdd Tabnine to your IDE (free)

How to use
Path
in
java.nio.file

Best Java code snippets using java.nio.file.Path (Showing top 20 results out of 42,219)

Refine searchRefine arrow

  • Files
  • Paths
  • Stream
  • URI
  • FileSystem
  • URL
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);
}
java.nio.filePath

Most used methods

  • toString
  • toFile
  • resolve
  • getFileName
  • toAbsolutePath
  • getParent
  • relativize
  • toUri
  • normalize
  • equals
  • startsWith
  • isAbsolute
  • startsWith,
  • isAbsolute,
  • getFileSystem,
  • getNameCount,
  • register,
  • toRealPath,
  • resolveSibling,
  • getName,
  • endsWith,
  • hashCode

Popular in Java

  • Running tasks concurrently on multiple threads
  • addToBackStack (FragmentTransaction)
  • onRequestPermissionsResult (Fragment)
  • startActivity (Activity)
  • GridBagLayout (java.awt)
    The GridBagLayout class is a flexible layout manager that aligns components vertically and horizonta
  • InetAddress (java.net)
    An Internet Protocol (IP) address. This can be either an IPv4 address or an IPv6 address, and in pra
  • ArrayList (java.util)
    ArrayList is an implementation of List, backed by an array. All optional operations including adding
  • PriorityQueue (java.util)
    A PriorityQueue holds elements on a priority heap, which orders the elements according to their natu
  • Stack (java.util)
    Stack is a Last-In/First-Out(LIFO) data structure which represents a stack of objects. It enables u
  • Location (org.springframework.beans.factory.parsing)
    Class that models an arbitrary location in a Resource.Typically used to track the location of proble
  • From CI to AI: The AI layer in your organization
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now