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" }
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"); } }
@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; } }
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); } } }
/** * This implementation returns the name of the file. * @see java.nio.file.Path#getFileName() */ @Override public String getFilename() { return this.path.getFileName().toString(); }
@Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { Files.createDirectories(dest.resolve(src.relativize(dir))); return FileVisitResult.CONTINUE; } @Override
@Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.copy(file, dest.resolve(src.relativize(file)), StandardCopyOption.REPLACE_EXISTING); return FileVisitResult.CONTINUE; } });
@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())); }
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()); }
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()); }
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); }
@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); } }
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 ); }
@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); } }
@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; }
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(); } }
@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" ) ); } }
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; }
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(); } }
@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); }