Java 8 : Get files from folder / subfolder [duplicate] - java

This question already has answers here:
Recursively list all files within a directory using nio.file.DirectoryStream;
(9 answers)
Closed 5 years ago.
I have this folders inside the resources folder of a SpringBoot app.
resources/files/a.txt
resources/files/b/b1.txt
resources/files/b/b2.txt
resources/files/c/c1.txt
resources/files/c/c2.txt
I want to get all the txt file, so this is my code:
ClassLoader classLoader = this.getClass().getClassLoader();
Path configFilePath = Paths.get(classLoader.getResource("files").toURI());
List<Path> atrackFileNames = Files.list(configFilePath)
.filter(s -> s.toString().endsWith(".txt"))
.map(Path::getFileName)
.sorted()
.collect(toList());
But I only get the file a.txt

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...-

Related

Quit text from string that references a path JAVA [duplicate]

This question already has answers here:
Get the filePath from Filename using Java
(5 answers)
Closed 2 years ago.
If i have a String that contains a path like
"D:\Folder\Folder2\file.txt"
, how can i remove the file and have only
"D:\Folder\Folder2"
Thank you for your time. :D
You could use the Apaches FilenameUtils..
This class defines six components within a filename (example
C:\dev\project\file.txt):
the prefix - C:\
the path - dev\project\
the full path -> C:\dev\project\
the name - file.txt
the base name - file
the extension - txt
So by using following code, you get the full path (without the filename):
getFullPath("D:\\Folder\\Folder2\\file.txt");
Please have a look at https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FilenameUtils.html
Java IO and NIO packages has classes for file handling - File and Path. All of these do same job to extract parent as Path, File or String and avoid hardcoding file separator:
import java.io.File:
File parent = new File("D:\\Folder\\Folder2\\file.txt").getParentFile();
String parent = new File("D:\\Folder\\Folder2\\file.txt").getParent();
import java.nio.file.Path:
Path parent = Path.of("D:\\Folder\\Folder2\\file.txt").getParent();
String parent = Path.of("D:\\Folder\\Folder2\\file.txt").getParent().toString();
String a = "D:\\Folder\\Folder2\\file.txt";
System.out.print(a.substring(0, a.lastIndexOf("\\")));

How to move some folders back after getting directory in java? [duplicate]

This question already has an answer here:
How can I go about getting the parent directory of a directory
(1 answer)
Closed 4 years ago.
I used this code and it showed my projects directory.
System.out.println("Present Project Directory : "+ System.getProperty("user.dir"));
for example: C:\Users\Yousuf\Documents\NetBeansProjects\Store Management System
what I want to do is move to C:\Users\Yousuf\Documents only two folders back from the directory obtained through this code. What should I do ?
this worked for me I got the parent directory of the parent directory...
System.out.println("Present Project Directory : "+ System.getProperty("user.dir"));
try
{
File file = new File(System.getProperty("user.dir")).getCanonicalFile();
System.out.println("Parent directory : " + file.getParent());
File file2 = new File(file.getParent()).getCanonicalFile();
System.out.println("Parent directory : " + file2.getParent());
} catch (Exception e)
{
System.out.println("error");
}
You can use the relative path ../../ to navigate 2 folders back. If you add that to the end of a path it's effective location will be 2 folders back.
After that if you want you can use the normalize function to remove redundant elements to give you the actual path 2 folders back. But if you just want to navigate to that folder there's no real need to normalize it.
Just put your path string in the place of originalPathString.
Path twoFoldersBack= Paths.get(originalPathString, "../../");
Or if you want the normalize the path:
Path twoFoldersBack= Paths.get(originalPathString, "../../").normalize();

Copy specific files from a directory and subdirectories into a target folder in mac

I have a directory structure in which i have some specific files (say mp3 files) organised directly or in subdirectories(upto n levels).
For example:
Music Folder
a.mp3
folder2
folder3
b.mp3
c.mp3
folder4
d.mp3
folder5
folder6
folder7
folder8
e.mp3
Now, what i require is to copy all files (.mp3 file) from all the folders and subfolders into another target folder. So my target folder would be like this:
targetFolder
a.mp3
b.mp3
c.mp3
d.mp3
e.mp3
I tried the answers from following questions:
Recursive copy of specific files in Unix/Linux?
and Copy all files with a certain extension from all subdirectories, but got copied the same directory(and subdirectories) structure.
Any help or suggestions?
cd "Music Folder"
find . -name "*.mp3" -exec cp {} /path/to/targetFolder \;
Using java code, i achieved this as follows:
Path start = Paths.get("/Users/karan.verma/Music/iTunes/iTunes Media/Music");
int maxDepth = 15;
try(Stream<Path> stream = Files.find(start,
maxDepth,
(path, attr) -> String.valueOf(path).endsWith(".mp3"))){
List<Path> fileName = stream
.sorted()
.filter(path -> String.valueOf(path).endsWith(".mp3"))
.collect(Collectors.toList());
for(Path p : fileName) {
Path path = Paths.get("/Users/karan.verma/Desktop/TestCopy/"+p.getFileName());
Files.copy(p, path,StandardCopyOption.REPLACE_EXISTING);
}
}catch(Exception e){
e.printStackTrace();
}

Get files inside folder [duplicate]

This question already has answers here:
How to read all files in a folder from Java?
(33 answers)
Get a list of resources from classpath directory
(15 answers)
Closed 6 years ago.
I am trying to read the content of the folder of my Java EE Spring application, but it always return me null. The folder I want is under src/main/resources folder and it`s called context. I try doing it this way :
File file = new File("src/main/resources/context")
But it always return me null for file.
You can use one of the following:
File file = new File("src/main/resources/context");
String[] list = file.list(); // returns an array of all file names in the context folder.
OR
File file = new File("src/main/resources/context");
File[] listFiles = file.listFiles(); // returns an array of all "file objects" for all files in the context folder.
Hope this helps!

How to scan a folder for files and their locations in java [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to scan a folder in Java?
I want to scan a given folder for all of the files within the folder and add the locations/paths (ex: "c:/users/peter/desktop/image.jpg") to an arraylist of strings. How could i do this? Thanks for the help
Peek around in the java.io.File API. There are at least three methods which may be of use:
listFiles()
isDirectory()
isFile()
You could try
File directory = new File("<Path to directory>");
String [] directoryContents = directory.list();
List<String> fileLocations = new ArrayList<String>();
for(String fileName: directoryContents) {
File temp = new File(String.valueOf(directory),fileName);
fileLocations.add(String.valueOf(temp));
}
Check out File.list()

Categories

Resources