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

The following examples show how to use java.nio.file.Files#list() . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: flink   File: UtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDeleteApplicationFiles() throws Exception {
	final Path applicationFilesDir = temporaryFolder.newFolder(".flink").toPath();
	Files.createFile(applicationFilesDir.resolve("flink.jar"));
	try (Stream<Path> files = Files.list(temporaryFolder.getRoot().toPath())) {
		assertThat(files.count(), equalTo(1L));
	}
	try (Stream<Path> files = Files.list(applicationFilesDir)) {
		assertThat(files.count(), equalTo(1L));
	}

	Utils.deleteApplicationFiles(Collections.singletonMap(
		YarnConfigKeys.FLINK_YARN_FILES,
		applicationFilesDir.toString()));
	try (Stream<Path> files = Files.list(temporaryFolder.getRoot().toPath())) {
		assertThat(files.count(), equalTo(0L));
	}
}
 
Example 2
Source Project: armeria   File: FileSystemHttpVfs.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected List<String> blockingList(Executor fileReadExecutor, String path) {
    path = normalizePath(path);
    try (Stream<Path> stream = Files.list(Paths.get(rootDir + path))) {
        return stream.filter(Files::isReadable)
                     .map(p -> {
                         final String fileName = p.getFileName().toString();
                         return Files.isDirectory(p) ? fileName + '/' : fileName;
                     })
                     .sorted(String.CASE_INSENSITIVE_ORDER)
                     .collect(toImmutableList());
    } catch (IOException e) {
        // Failed to retrieve the listing.
        return ImmutableList.of();
    }
}
 
Example 3
@Test
public void async() throws Exception {
    // create derivate
    create();
    MCRSessionMgr.getCurrentSession().commitTransaction();

    // execute threads
    MCRSystemUserInformation systemUser = MCRSystemUserInformation.getSystemUserInstance();
    ExecutorService executorService = Executors.newFixedThreadPool(3);
    Future<Exception> future1 = executorService
        .submit(new MCRFixedUserCallable<>(new CopyTask("anpassbar.jpg", derivate), systemUser));
    Future<Exception> future2 = executorService
        .submit(new MCRFixedUserCallable<>(new CopyTask("nachhaltig.jpg", derivate), systemUser));
    Future<Exception> future3 = executorService
        .submit(new MCRFixedUserCallable<>(new CopyTask("vielseitig.jpg", derivate), systemUser));
    throwException(future1.get(5, TimeUnit.SECONDS));
    throwException(future2.get(5, TimeUnit.SECONDS));
    throwException(future3.get(5, TimeUnit.SECONDS));
    try (Stream<Path> streamPath = Files.list(MCRPath.getPath(derivate.getId().toString(), "/"))) {
        assertEquals("the derivate should contain three files", 3, streamPath.count());
    }

    executorService.awaitTermination(1, TimeUnit.SECONDS);
}
 
Example 4
Source Project: indexr   File: RTSGroup.java    License: Apache License 2.0 6 votes vote down vote up
public static State getState(Path path) throws IOException {
    if (!Files.exists(path)) {
        return Begin;
    }
    try (Stream<Path> paths = Files.list(path)) {
        Set<String> stateFiles = paths
                .map(p -> p.getFileName().toString())
                .filter(n -> n.startsWith("_ST_") || n.startsWith("_st_"))
                .collect(Collectors.toSet());
        State stat = Begin;
        for (State st : State.values()) {
            if (stateFiles.contains(st.fileName) || stateFiles.contains(st.fileName.toLowerCase())) {
                stat = st;
            }
        }
        return stat;
    }
}
 
Example 5
private void stopWithSavepointNormalExecutionHelper(final boolean terminate) throws Exception {
	setUpJobGraph(NoOpBlockingStreamTask.class, RestartStrategies.noRestart());

	final CompletableFuture<String> savepointLocationFuture = stopWithSavepoint(terminate);

	assertThat(getJobStatus(), equalTo(JobStatus.RUNNING));

	finishingLatch.trigger();

	final String savepointLocation = savepointLocationFuture.get();
	assertThat(getJobStatus(), equalTo(JobStatus.FINISHED));

	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()));
}
 
Example 6
Source Project: hadoop-ozone   File: TarContainerPacker.java    License: Apache License 2.0 5 votes vote down vote up
private void includePath(Path dir, String subdir,
    ArchiveOutputStream archiveOutput) throws IOException {

  try (Stream<Path> dirEntries = Files.list(dir)) {
    for (Path path : dirEntries.collect(toList())) {
      String entryName = subdir + "/" + path.getFileName();
      includeFile(path.toFile(), entryName, archiveOutput);
    }
  }
}
 
Example 7
private Stream<Path> getLibrarySearchFiles(Path librarySearchPath) {
	if (Files.isDirectory(librarySearchPath)) {
		try {
			return Files.list(librarySearchPath);
		} catch (IOException e) {
			AmidstLogger.error(e, "Error while reading library directory " + librarySearchPath);
		}
	}
	return Stream.empty();
}
 
Example 8
@Override
public List<? extends Resource> getChildren() throws NotAuthorizedException, BadRequestException {
	if(children==null)
	{
			children = new ArrayList<>();
			
			if(root)
			{
				fs.getRootDirectories().forEach(p->children.add(new MTGDavFolderResource((MTGPath)p, fs, false,user,pass)));
				return children;
			}
			else
			{
				try (Stream<Path> s = Files.list(mtgpath))
				{
					s.forEach(p->{
						if(((MTGPath)p).isCard())
							children.add(new MTGDavFileResource((MTGPath)p, fs, user,pass));
						else
							children.add(new MTGDavFolderResource((MTGPath)p, fs, false,user,pass));
					});
				} catch (IOException e) {
					logger.error(e);
				}
					
			}
	}
	return children;
}
 
Example 9
Source Project: LuckPerms   File: SubjectStorage.java    License: MIT License 5 votes vote down vote up
/**
 * Returns a set of all known collections
 *
 * @return the identifiers of all known collections
 */
public Set<String> getSavedCollections() {
    if (!Files.exists(this.container)) {
        return ImmutableSet.of();
    }

    try (Stream<Path> s = Files.list(this.container)) {
        return s.filter(p -> Files.isDirectory(p))
                .map(p -> p.getFileName().toString())
                .collect(ImmutableCollectors.toSet());
    } catch (IOException e) {
        e.printStackTrace();
        return ImmutableSet.of();
    }
}
 
Example 10
@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()));
}
 
Example 11
public TokenInfoDictionaryWriter build(Path dir) throws IOException {
  try (Stream<Path> files = Files.list(dir)) {
    List<Path> csvFiles = files
        .filter(path -> path.getFileName().toString().endsWith(".csv"))
        .sorted()
        .collect(Collectors.toList());
    return buildDictionary(csvFiles);
  }
}
 
Example 12
Source Project: cassandra-backup   File: SSTableUtils.java    License: Apache License 2.0 5 votes vote down vote up
private static Stream<? extends Path> tryListFiles(Path path) {
    try {
        return Files.list(path);
    } catch (IOException e) {
        logger.error("Failed to retrieve the file(s)", e);
        return Stream.empty();
    }
}
 
Example 13
Source Project: haven-platform   File: NetCollector.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void fill(SysInfo info) throws Exception {
    // /sys/class/net/eth0/statistics/rx_bytes
    // /sys/class/net/eth0/statistics/tx_bytes
    Map<String, SysInfo.Net> nets = info.getNet();
    for(Path devPath: (Iterable<Path>)(Files.list(path)::iterator)) {
        String dev = devPath.getFileName().toString();
        SysInfo.Net net = new SysInfo.Net();
        readNet(devPath, net);
        nets.put(dev, net);
    }
}
 
Example 14
Source Project: manifold   File: PathUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static Path[] listFiles( Path path )
{
  try( Stream<Path> list = Files.list( path ) )
  {
    return list.toArray( Path[]::new );
  }
  catch( IOException e )
  {
    throw new RuntimeException( e );
  }
}
 
Example 15
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();
	}
}
 
Example 16
void run() throws IOException {
    Path src = Paths.get(System.getProperty("test.src"), "tests");

    try (Stream<Path> tests = Files.list(src)) {
        tests.map(p -> Files.isRegularFile(p) ? Stream.of(p) : silentWalk(p))
             .forEach(this :: runTest);
    }
}
 
Example 17
private List<Path> resourceDirs() throws IOException {
    try (Stream<Path> stream = Files.list(actual)) {
        return stream.filter(Files::isDirectory)
                     .map(path -> path.resolve("resources")).filter(Files::exists)
                     .collect(Collectors.toList());
    }
}
 
Example 18
Source Project: java8-tutorial   File: Files1.java    License: MIT License 5 votes vote down vote up
private static void testList() throws IOException {
    try (Stream<Path> stream = Files.list(Paths.get(""))) {
        String joined = stream
                .map(String::valueOf)
                .filter(path -> !path.startsWith("."))
                .sorted()
                .collect(Collectors.joining("; "));
        System.out.println("list(): " + joined);
    }
}
 
Example 19
Source Project: curiostack   File: UpdateIntelliJSdksTask.java    License: MIT License 4 votes vote down vote up
@TaskAction
public void exec() throws IOException {
  Path userHome = Paths.get(System.getProperty("user.home"));
  final List<Path> intelliJFolders;
  try (var files = Files.list(userHome)) {
    intelliJFolders =
        files
            .filter(
                path ->
                    Files.isDirectory(path)
                        && (path.getFileName().toString().startsWith(".IntelliJIdea")
                            || path.getFileName().toString().startsWith(".IdeaIC")))
            .sorted()
            .collect(toImmutableList());
  }

  final Path intelliJFolder;
  if (!intelliJFolders.isEmpty()) {
    intelliJFolder = Iterables.getLast(intelliJFolders);
  } else {
    getProject()
        .getLogger()
        .info("No IntelliJ config folder found, writing to default location.");
    intelliJFolder = userHome.resolve(LATEST_INTELLIJ_CONFIG_FOLDER);
  }

  getProject()
      .getLogger()
      .info("Updating IntelliJ folder {}, found folders {}", intelliJFolder, intelliJFolders);

  String javaVersion = ToolDependencies.getOpenJdkVersion(getProject());
  String majorVersion =
      javaVersion.startsWith("zulu")
          ? JavaVersion.toVersion(javaVersion.substring("zulu".length())).getMajorVersion()
          : JavaVersion.toVersion(javaVersion).getMajorVersion();

  String java8Version = ToolDependencies.getOpenJdk8Version(getProject());
  final String jdk8FolderSuffix;
  switch (new PlatformHelper().getOs()) {
    case WINDOWS:
      jdk8FolderSuffix = "win_x64";
      break;
    case MAC_OSX:
      jdk8FolderSuffix = "macosx_x64";
      break;
    case LINUX:
      jdk8FolderSuffix = "linux_x64";
      break;
    default:
      throw new IllegalStateException("Unknown OS");
  }
  String jdk8FolderName = java8Version + "/" + java8Version + "-" + jdk8FolderSuffix;

  var jdkTable =
      Files.createDirectories(intelliJFolder.resolve("config/options")).resolve("jdk.table.xml");
  updateConfig(
      jdkTable,
      "jdk-" + javaVersion,
      majorVersion,
      "curiostack/openjdk-intellij-table-snippet.template.xml",
      ImmutableMap.of(
          "javaVersion", javaVersion, "javaModules", JAVA_MODULES, "majorVersion", majorVersion),
      getProject());
  updateConfig(
      jdkTable,
      jdk8FolderName,
      "1.8",
      "curiostack/openjdk-8-intellij-table-snippet.template.xml",
      ImmutableMap.of("javaVersion", java8Version, "javaModules", JAVA_8_JARS),
      getProject());

  updateGoSdk(intelliJFolder, getProject());
  updateGoPath(intelliJFolder, getProject());
}
 
Example 20
Source Project: protools   File: ToolPath.java    License: Apache License 2.0 4 votes vote down vote up
public static Stream<Path> dirStream(Path dir) throws IOException {
    return Files.list(dir);
}