Path.getFilename() does not return a String, but a Path object, do this:
getFilename().toString().equals("workspace")
Answer from David on Stack OverflowPath.getFilename() does not return a String, but a Path object, do this:
getFilename().toString().equals("workspace")
Use the following and look at the console. Maybe none of your files contains workspace in it
Files.find(p,maxDepth,(path, basicFileAttributes) -> {
if (String.valueOf(path).equals("workspace")) {
System.out.println("FOUND : " + path);
return true;
}
System.out.println("\tNOT VALID : " + path);
return false;
});
Please have a look at Files.find method.
try (Stream<Path> stream = Files.find(Paths.get("Folder 1"), 5,
(path, attr) -> path.getFileName().toString().equals("Myfile.txt") )) {
System.out.println(stream.findAny().isPresent());
} catch (IOException e) {
e.printStackTrace();
}
public static String getAdobeExePath(String basePath, String exeName) {
File[] files = new File(basePath).listFiles();
String foundPath;
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
foundPath = getAdobeExePath(files[i].getAbsolutePath(), exeName);
if (foundPath != null) {
return foundPath;
}
}else {
if (exeName.equals(files[i].getName())) {
return files[i].getAbsolutePath();
}
}
}
return null;
}
This is using recursion.
What you want is File.listFiles(FileNameFilter filter).
That will give you a list of the files in the directory you want that match a certain filter.
The code will look similar to:
// your directory
File f = new File("C:\\example");
File[] matchingFiles = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith("temp") && name.endsWith("txt");
}
});
You can use a FilenameFilter, like so:
File dir = new File(directory);
File[] matches = dir.listFiles(new FilenameFilter()
{
public boolean accept(File dir, String name)
{
return name.startsWith("temp") && name.endsWith(".txt");
}
});
you can try something like this:
import java.io.*;
import java.util.*;
class FindFile
{
public void findFile(String name,File file)
{
File[] list = file.listFiles();
if(list!=null)
for (File fil : list)
{
if (fil.isDirectory())
{
findFile(name,fil);
}
else if (name.equalsIgnoreCase(fil.getName()))
{
System.out.println(fil.getParentFile());
}
}
}
public static void main(String[] args)
{
FindFile ff = new FindFile();
Scanner scan = new Scanner(System.in);
System.out.println("Enter the file to be searched.. " );
String name = scan.next();
System.out.println("Enter the directory where to search ");
String directory = scan.next();
ff.findFile(name,new File(directory));
}
}
Here is the output:
J:\Java\misc\load>java FindFile
Enter the file to be searched..
FindFile.java
Enter the directory where to search
j:\java\
FindFile.java Found in->j:\java\misc\load
Using Java 8+ features we can write the code in few lines:
protected static Collection<Path> find(String fileName, String searchDirectory) throws IOException {
try (Stream<Path> files = Files.walk(Paths.get(searchDirectory))) {
return files
.filter(f -> f.getFileName().toString().equals(fileName))
.collect(Collectors.toList());
}
}
Files.walk returns a Stream<Path> which is "walking the file tree rooted at" the given searchDirectory. To select the desired files only a filter is applied on the Stream files. It compares the file name of a Path with the given fileName.
Note that the documentation of Files.walk requires
This method must be used within a try-with-resources statement or similar control structure to ensure that the stream's open directories are closed promptly after the stream's operations have completed.
I'm using the try-resource-statement.
For advanced searches an alternative is to use a PathMatcher:
protected static Collection<Path> find(String searchDirectory, PathMatcher matcher) throws IOException {
try (Stream<Path> files = Files.walk(Paths.get(searchDirectory))) {
return files
.filter(matcher::matches)
.collect(Collectors.toList());
}
}
An example how to use it to find a certain file:
public static void main(String[] args) throws IOException {
String searchDirectory = args[0];
String fileName = args[1];
PathMatcher matcher = FileSystems.getDefault().getPathMatcher("regex:.*" + fileName);
Collection<Path> find = find(searchDirectory, matcher);
System.out.println(find);
}
More about it: Oracle Finding Files tutorial
Path configFilePath = FileSystems.getDefault()
.getPath("C:\\Users\\sharmaat\\Desktop\\issue\\stores");
List<Path> fileWithName = Files.walk(configFilePath)
.filter(s -> s.toString().endsWith(".java"))
.map(Path::getFileName).sorted().collect(Collectors.toList());
for (Path name : fileWithName) {
// printing the name of file in every sub folder
System.out.println(name);
}
Files.list(path) method returns only stream of files in directory. And the method listing is not recursive.
Instead of that you should use Files.walk(path). This method walks through all file tree rooted at a given starting directory.
More about it:
https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#walk-java.nio.file.Path-java.nio.file.FileVisitOption...-
Yes you can do it. Assuming you have paths as a List of String objects, you can do it like so,
List<String> paths = ...;
paths.stream().map(path -> {
try (Stream<Path> stream = Files.list(Paths.get(path))) {
return stream.filter(p -> !p.toFile().isDirectory()).filter(p -> p.toString().endsWith(".json"))
.map(Path::toString).collect(Collectors.joining("\n"));
} catch (IOException e) {
// Log your ERROR here.
e.printStackTrace();
}
return "";
}).forEach(System.out::println);
In case if you need to get rid of the new-line character, then it can be done like this too.
paths.stream().map(path -> {
try (Stream<Path> stream = Files.walk(Paths.get(path))) {
return stream.filter(p -> !p.toFile().isDirectory()).filter(p -> p.toString().endsWith(".json"))
.map(Path::toString).collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
return Collections.emptyList();
}).flatMap(List::stream).forEach(System.out::println);
Here you get all the .json file names for each path into a List, and then flatten them into a flat stream of String objects before printing. Notice that the additional step involved in this approach which is flatMap.
That’s what flatMap is for.
If you have a collection of Path instances in path, you may use
paths.stream()
.flatMap(path -> {
try { return Files.find(path, Integer.MAX_VALUE,
(p, attrs) -> attrs.isRegularFile() && p.toString().endsWith(".json")); }
catch (IOException ex) { throw new UncheckedIOException(ex); }
})
.forEach(System.out::println);
It is a bit clumsy due to the fact that we have to deal with the checked IOException declared by find here. Rethrowing it as UncheckedIOException is the simplest choice as that’s what the stream returned by find will do anyway if an I/O problem occurs while processing the stream. Compare with the documentation of find
If an
IOExceptionis thrown when accessing the directory after returned from this method, it is wrapped in anUncheckedIOExceptionwhich will be thrown from the method that caused the access to take place.
So doing the same within our function simplifies the caller’s error handling, as it just has to handle UncheckedIOExceptions.
There is no way to use try(…) here, but that’s exactly the reason why flatMap will remove this burden from us. As its documentation states:
Each mapped stream is closed after its contents have been placed into this stream.
So, once our function has returned the sub-stream, the Stream mplementation will do the right thing for us.
You may chain arbitrary stream operations in place of .forEach(System.out::println); to process all elements of the flattened stream like a single stream.
If your input collection contains instances of String instead of Path, you may simply prepend paths.stream().map(Paths::get) instead of paths.stream() to the flatMap operation.