Find directory and get its absolute path [duplicate] - java

What is the best way to find a directory with a specific name in Java? The directory that I am looking for can be located either in the current directory or one of its subdirectories.

In Java 8 via the streams API:
Optional<Path> hit = Files.walk(myPath)
.filter(file -> file.getFileName().equals(myName))
.findAny();
The #walk is lazy, so any short-circuiting terminal operation will optimize the IO required.

To walk the file tree, FileVisitor interface can be used.
Please see the tutorial. Please see Find sample codes also.

Your solution will include the use of File.listFiles(String)
java.io.File API reference

As you mentioned recursion should cater to this requirement
import java.io.File;
public class CheckFile {
private static boolean foundFolder = false;
public static void main(String[] args) {
File dir = new File("currentdirectory");
findDirectory(dir);
}
private static void findDirectory(File parentDirectory) {
if(foundFolder) {
return;
}
File[] files = parentDirectory.listFiles();
for (File file : files) {
if (file.isFile()) {
continue;
}
if (file.getName().equals("folderNameToFind")) {
foundFolder = true;
break;
}
if(file.isDirectory()) {
findDirectory(file);
}
}
}
}

Something like:
public static final File findIt(File rootDir, String fileName) {
File[] files = rootDir.listFiles();
List<File> directories = new ArrayList<File>(files.length);
for (File file : files) {
if (file.getName().equals(fileName)) {
return file;
} else if (file.isDirectory()) {
directories.add(file);
}
}
for (File directory : directories) {
File file = findIt(directory);
if (file != null) {
return file;
}
}
return null;
}

Divide and conquer? A naive approach: For every directory, you may start a task, it does the following:
list every directory
if the list contains a matching directory, prints and exit the application
start a task for every directory.

Or, you should use the concept of Recursively search the file until it found: Here is the Code:
String name; //to hold the search file name
public String listFolder(File dir) {
int flag;
File[] subDirs = dir.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.isDirectory();
}
});
System.out.println("File of Directory: " + dir.getAbsolutePath());
flag = Listfile(dir);
if (flag == 0) {
System.out.println("File Found in THe Directory: " + dir.getAbsolutePath());
Speak("File Found in THe Directory: !!" + dir.getAbsolutePath());
return dir.getAbsolutePath();
}
for (File folder : subDirs) {
listFolder(folder);
}
return null;
}
private int Listfile(File dir) {
boolean ch = false;
File[] files = dir.listFiles();
for (File file : files) {
Listfile(file);
if (file.getName().indexOf(name.toLowerCase()) != -1) {//check all in lower case
System.out.println(name + "Found Sucessfully!!");
ch = true;
}
}
if (ch) {
return 1;
} else {
return 0;
}
}

Related

How to search entire hard drive for a specific file (Java Eclipse)?

public static void fileSearcher() throws IOException {
File dire = new File ("C:/");
String[] allFile = dire.list();
for (int i = 0;i<10;i++) {
String FilIn = allFile[i]; // here is where I need to scan entire pc for file
if(FilIn.equals("eclipse.exe")){
System.out.println("Found Eclipse!");
break;
}
else {
System.out.println("Eclipse not found on local drive.");
}
Is there a simple way to scan an entire HHD/SSD for a specific file ?
This will do the job for you and it works too when there are multiple drives or partitions. It will also search for additional files with that same name.
import java.io.File;
import javax.swing.filechooser.FileSystemView;
public class HardDiskSearcher {
private static boolean fileFound = false;
private static String searchTerm = "eclipse.exe";
public static void main(String[] args) {
fileFound = false;
File[] systemRoots = File.listRoots();
FileSystemView fsv = FileSystemView.getFileSystemView();
for (File root: systemRoots) {
if (fsv.getSystemTypeDescription(root).equals("Local Disk")) {
File[] filesFromRoot = root.listFiles();
recursiveSearch(searchTerm, filesFromRoot);
}
}
System.out.println("File you searched for was found? : " + fileFound);
}
private static void recursiveSearch(String searchTerm, File... files) {
for (File file: files) {
if (file.isDirectory()) {
File[] filesInFolder = file.listFiles();
if (filesInFolder != null) {
for (File f : filesInFolder) {
if (f.isFile()) {
if (isTheSearchedFile(f, searchTerm)) {
fileFound = true;
}
}
}
for (File f : filesInFolder) {
if (f.isDirectory()) {
recursiveSearch(searchTerm, f);
}
}
}
}
else if (isTheSearchedFile(file, searchTerm)) {
fileFound = true;
}
}
}
private static boolean isTheSearchedFile(File file, String searchTerm) {
if (file.isFile() && (searchTerm.equals(file.getName())) ) {
System.out.println("The file you searched for has been found! " +
"It was found at: " + file.getAbsolutePath());
return true;
}
return false;
}
}
I am not 100% sure about why the if-statement (filesInFolder != null) is necessary here but i suspect Windows returns null when trying to list files from specific system folder or something.

Java - Iterate over all files in directory

I want to find all the txt files in directory and in the nested sub-directories. If found, I want to move that from one location to another.
The below code works fine, if i don't have any nested sub-directories.
The problem with the below code is, Once it find the nested directories it return the file only from that particular nested sub-directory.
But I want all the txt files in my directory ( parent and its nested sub-directories ).
public class FilesFindingInDirectory {
static ArrayList<File> al = new ArrayList<File>();
static File fileLocation = null;
public static void main(String[] args) throws IOException {
File filePath = new File("C:\\Users\\Downloads");
File[] listingAllFiles = filePath.listFiles();
ArrayList<File> allFiles = iterateOverFiles(listingAllFiles);
for (File file : allFiles) {
if(file != null) {
String fileName = file.getName();
String sourceFilepath = file.getAbsolutePath();
File targetFilePath = new File("D:\\TestFiles");
String targetPath = targetFilePath.getPath();
Files.move(Paths.get(sourceFilepath), Paths.get("D:\\TestFiles\\" + fileName));
}
}
}
public static ArrayList<File> iterateOverFiles(File[] files) {
for (File file : files) {
if (file.isDirectory()) {
iterateOverFiles(file.listFiles());// Calls same method again.
} else {
fileLocation = findFileswithTxtExtension(file);
if(fileLocation != null) {
System.out.println(fileLocation);
al.add(fileLocation);
}
}
}
return al;
}
public static File findFileswithTxtExtension(File file) {
if(file.getName().toLowerCase().endsWith("txt")) {
return file;
}
return null;
}
}
You're already using the nio Files API to move the files, why not using it to iterate over the files?
List<Path> txtFiles = Files.walk(Paths.get("C:\\Users\\Downloads"))
//use to string here, otherwise checking for path segments
.filter(p -> p.toString().endsWith(".txt"))
.collect(Collectors.toList());
If you don't need that intermediary list, you could as well run your move operation in a foreach terminal operation
Files.walk(Paths.get("C:\\Users\\Downloads"))
.filter(p -> p.toString().endsWith(".txt"))
.forEach(p -> {
try {
Files.move(p, Paths.get("D:\\TestFiles", p.getFileName().toString()));
} catch (IOException e) {
e.printStackTrace();
}
});
From your recursive function remove this line:
return al;
change this line to just call the recursive function:
ArrayList<File> allFiles = iterateOverFiles(listingAllFiles);
to
iterateOverFiles(listingAllFiles);
and finally change your for loop to iterate over the static field al.
for (File file : allFiles) {
to
for (File file : al) {
Explanation: There are numerous ways to write recursion for this problem. In this case you have a global variable for collecting the results. Each iteration should add to that global result, and simply return. At the end of all recursion calls, the global variable will contain all the results.
You are properly calling the function recursively, but you're then ignoring its return value. Instead, you should append it to the result list:
public static List<File> iterateOverFiles(File[] files) {
List<File> result = new ArrayList<>();
for (File file : files) {
if (file.isDirectory()) {
result.addAll(iterateOverFiles(file.listFiles()); // Here!
} else {
fileLocation = findFileswithTxtExtension(file);
if(fileLocation != null) {
result.add(fileLocation);
}
}
}
return result;
}
Just iterate over a directory, skipping any non-directory entries and entries that do not have the desired extension. Add all files with the correct extension to a result, and do that recursively for each directory.
public class FilesFindingInDirectory {
public static void main(String[] args) throws IOException {
File filePath = new File("C:\\Users\\Downloads");
Collection<File> allFiles = findFiles(filePath, ".txt");
allFiles.forEach(file -> {
String fileName = file.getName();
String sourceFilepath = file.getAbsolutePath();
File targetFilePath = new File("D:\\TestFiles");
String targetPath = targetFilePath.getPath();
Files.move(Paths.get(sourceFilepath), Paths.get("D:\\TestFiles\\" + fileName));
}
}
}
public static List<File> findFiles(File dir, String extension) {
File[] files = dir.listFiles(f -> f.isDirectory() || f.getName().toLowerCase().endsWith(extension);
ArrayList<File> result = new ArrayList<>();
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
result.addAll(findFiles(file, extension);
} else {
result.add(file);
}
}
return result;
}
}

how to filter a file with apk extension in sdcard?

I want to filter files stored in my phone with the .apk extension. I have tried the below code but it filters files found only in sdcard/file.apk
but I want it to filter the file by searching into the sub directories of sdcard also.
For example if there is an apk file inside sdcard/download/mm.apk it should filter it and also if there is another file in sdcard/New Folder/ABC/cc.apk it should filter it too.
How can I do that? thank you for your help...
ExtFilter apkFilter = new ExtFilter("apk");
File file[] =Environment.getExternalStorageDirectory().listFiles(apkFilter);
Log.i("InstallApk","Filter applied. Size: "+ file.length);
for (int i=0; i < file.length; i++)
{
Log.i("InstallApk",
"FileName:" + file[i].getName());
}
ArrayAdapter af=new ArrayAdapter<File>(this,android.R.layout.simple_list_item_1,android.R.id.text1,file);
ListView ll=(ListView) findViewById(R.id.mainListView1);
ll.setAdapter(af);
}
class ExtFilter implements
FilenameFilter {
String ext;
public ExtFilter(String ext) {
this.ext = "." + ext;
}
public boolean accept(File dir, String name)
{
return name.endsWith(ext);
}
}
You have to do it recursively. It is not enough to check for the extension, you must also verify that it is a regular file cos I can as well name a directory dir.apk. Verifying that it is a regular file is also not enough since one can name any file with any extension. Regardless, checking that it is a regular file should be enough without consideration of the intended action on these files.
public void someFunction() {
List<File> apkFiles = getApkFiles(Environment.getExternalStorageDirectory(), new ApkSearchFilter());
File file[] = apkFiles.toArray(new File[apkFiles.size()]);
Log.i("InstallApk", "Filter app\"lied. Size: " + file.length);
for (File aFile : file) {
Log.i("InstallApk", "FileName:" + aFile.getName());
}
}
List<File> getApkFiles(File file, ApkSearchFilter filter) {
if (filter.isApk(file))
return Collections.singletonList(file);
else if (filter.isDirectory(file)) {
LinkedList<File> files = new LinkedList<>();
for (File subFile : file.listFiles()) {
files.addAll(getApkFiles(subFile, filter));
}
return files;
} else return Collections.emptyList();
}
class ApkSearchFilter implements FileFilter {
boolean isApk(File file) {
return !file.isDirectory() && file.getName().matches(".*\\.apk");
}
boolean isDirectory(File file) {
return file.isDirectory();
}
#Override
public boolean accept(File file) {
return isDirectory(file) || isApk(file);
}
}
This is one in many way you can try, don't forget to add permission in manifest:
private List<String> ReadSDCard()
{
File f = new File("your path"); // Environment.getExternalStorageDirectory()
File[] files=f.listFiles();
for(int i=0; i<files.length; i++)
{
File file = files[i];
String filePath = file.getPath();
if(filePath.endsWith(".apk"))
tFileList.add(filePath);
}
return tFileList;
}

skip duplicate file using java

Can anyone help me to skip file having extension "read" in my code ?
I have two files in my folder:
123.csv
123.csv.read
After execution every csv file is converted into ".csv.read", but if the same file comes again, that file should be skipped.
Like this file (123.csv.read) has been processed already, so if same new file(123.csv) comes, I want to be skipped that file.
In my code below, after 123.csv file is processed, the folder has only one file 123.csv.read. break is not behaving as I was expecting.
context.Str = ((String)globalMap.get("tFileList_1_CURRENT_FILEPATH"));
String extension = context.Str.substring(context.Str.lastIndexOf(".") + 1);
if (extension.equals("read"))
{
break;
}
else {
System.out.println("Good File to Process");
}
public static void listFile(final String folder, final String ext) {
ExtFilter filter = new ExtFilter(ext);
File dir = new File(folder);
if (dir.isDirectory() == false) {
System.out.println("Directory does not exists : " + FindFileExtension.FILE_DIR);
return;
}
// list out all the file name and filter by the extension
String[] list = dir.list(filter);
if (list.length == 0) {
System.out.println("no files end with : " + ext);
return;
}
for (String file : list) {
String temp = new StringBuffer(FindFileExtension.FILE_DIR).append(File.separator).append(file).toString();
System.out.println("file : " + temp);
// do your stuff here this file is not processed
}
}
public static class ExtFilter implements FilenameFilter {
private String ext;
public ExtFilter(final String ext) {
this.ext = ext;
}
public boolean accept(final File dir, final String name) {
return (name.endsWith(this.ext));
}
}
You can do something like that,it might help you
You can try this:
For example 123.csv file came again, then you check this if exist in read folder
if(!new File(123.csv+".read").exist()) {
// if this file is not exist, then it means that this has not been processed
// process the file
} else {
// do some other staff
}
Edit: Or you can try this
public static void main(String[] args) throws Exception {
File dir = new File("your_path");
File[] processedFiles = dir.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.getName().contains("read");
}
});
List<File> files = Arrays.asList(processedFiles);
File[] noneProcessedFiles = dir.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return !pathname.getName().contains("read");
}
});
for (File file : noneProcessedFiles) {
if (!files.stream().findAny().get().getName().contains(file.getName())) {
// process the file....
System.out.println("Not found ... " + file.getName());
} else {
// do some other staff....
System.out.println("Fount the file");
}
}
}

How to read all files in a folder from Java?

Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
How to read all the files in a folder through Java? It doesn't matter which API.
public void listFilesForFolder(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
System.out.println(fileEntry.getName());
}
}
}
final File folder = new File("/home/you/Desktop");
listFilesForFolder(folder);
Files.walk API is available from Java 8.
try (Stream<Path> paths = Files.walk(Paths.get("/home/you/Desktop"))) {
paths
.filter(Files::isRegularFile)
.forEach(System.out::println);
}
The example uses try-with-resources pattern recommended in API guide. It ensures that no matter circumstances the stream will be closed.
File folder = new File("/Users/you/folder/");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if (file.isFile()) {
System.out.println(file.getName());
}
}
In Java 8 you can do this
Files.walk(Paths.get("/path/to/folder"))
.filter(Files::isRegularFile)
.forEach(System.out::println);
which will print all files in a folder while excluding all directories. If you need a list, the following will do:
Files.walk(Paths.get("/path/to/folder"))
.filter(Files::isRegularFile)
.collect(Collectors.toList())
If you want to return List<File> instead of List<Path> just map it:
List<File> filesInFolder = Files.walk(Paths.get("/path/to/folder"))
.filter(Files::isRegularFile)
.map(Path::toFile)
.collect(Collectors.toList());
You also need to make sure to close the stream! Otherwise you might run into an exception telling you that too many files are open. Read here for more information.
All of the answers on this topic that make use of the new Java 8 functions are neglecting to close the stream. The example in the accepted answer should be:
try (Stream<Path> filePathStream=Files.walk(Paths.get("/home/you/Desktop"))) {
filePathStream.forEach(filePath -> {
if (Files.isRegularFile(filePath)) {
System.out.println(filePath);
}
});
}
From the javadoc of the Files.walk method:
The returned stream encapsulates one or more DirectoryStreams. If
timely disposal of file system resources is required, the
try-with-resources construct should be used to ensure that the
stream's close method is invoked after the stream operations are completed.
One remark according to get all files in the directory.
The method Files.walk(path) will return all files by walking the file tree rooted at the given started file.
For instance, there is the next file tree:
\---folder
| file1.txt
| file2.txt
|
\---subfolder
file3.txt
file4.txt
Using the java.nio.file.Files.walk(Path):
Files.walk(Paths.get("folder"))
.filter(Files::isRegularFile)
.forEach(System.out::println);
Gives the following result:
folder\file1.txt
folder\file2.txt
folder\subfolder\file3.txt
folder\subfolder\file4.txt
To get all files only in the current directory use the java.nio.file.Files.list(Path):
Files.list(Paths.get("folder"))
.filter(Files::isRegularFile)
.forEach(System.out::println);
Result:
folder\file1.txt
folder\file2.txt
import java.io.File;
public class ReadFilesFromFolder {
public static File folder = new File("C:/Documents and Settings/My Documents/Downloads");
static String temp = "";
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Reading files under the folder "+ folder.getAbsolutePath());
listFilesForFolder(folder);
}
public static void listFilesForFolder(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
// System.out.println("Reading files under the folder "+folder.getAbsolutePath());
listFilesForFolder(fileEntry);
} else {
if (fileEntry.isFile()) {
temp = fileEntry.getName();
if ((temp.substring(temp.lastIndexOf('.') + 1, temp.length()).toLowerCase()).equals("txt"))
System.out.println("File= " + folder.getAbsolutePath()+ "\\" + fileEntry.getName());
}
}
}
}
}
In Java 7 and higher you can use listdir
Path dir = ...;
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
for (Path file: stream) {
System.out.println(file.getFileName());
}
} catch (IOException | DirectoryIteratorException x) {
// IOException can never be thrown by the iteration.
// In this snippet, it can only be thrown by newDirectoryStream.
System.err.println(x);
}
You can also create a filter that can then be passed into the newDirectoryStream method above
DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {
public boolean accept(Path file) throws IOException {
try {
return (Files.isRegularFile(path));
} catch (IOException x) {
// Failed to determine if it's a file.
System.err.println(x);
return false;
}
}
};
For other filtering examples, [see documentation].(http://docs.oracle.com/javase/tutorial/essential/io/dirs.html#glob)
private static final String ROOT_FILE_PATH="/";
File f=new File(ROOT_FILE_PATH);
File[] allSubFiles=f.listFiles();
for (File file : allSubFiles) {
if(file.isDirectory())
{
System.out.println(file.getAbsolutePath()+" is directory");
//Steps for directory
}
else
{
System.out.println(file.getAbsolutePath()+" is file");
//steps for files
}
}
Just walk through all Files using Files.walkFileTree (Java 7)
Files.walkFileTree(Paths.get(dir), new SimpleFileVisitor<Path>() {
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
System.out.println("file: " + file);
return FileVisitResult.CONTINUE;
}
});
If you want more options, you can use this function which aims to populate an arraylist of files present in a folder. Options are : recursivility and pattern to match.
public static ArrayList<File> listFilesForFolder(final File folder,
final boolean recursivity,
final String patternFileFilter) {
// Inputs
boolean filteredFile = false;
// Ouput
final ArrayList<File> output = new ArrayList<File> ();
// Foreach elements
for (final File fileEntry : folder.listFiles()) {
// If this element is a directory, do it recursivly
if (fileEntry.isDirectory()) {
if (recursivity) {
output.addAll(listFilesForFolder(fileEntry, recursivity, patternFileFilter));
}
}
else {
// If there is no pattern, the file is correct
if (patternFileFilter.length() == 0) {
filteredFile = true;
}
// Otherwise we need to filter by pattern
else {
filteredFile = Pattern.matches(patternFileFilter, fileEntry.getName());
}
// If the file has a name which match with the pattern, then add it to the list
if (filteredFile) {
output.add(fileEntry);
}
}
}
return output;
}
Best, Adrien
File directory = new File("/user/folder");
File[] myarray;
myarray=new File[10];
myarray=directory.listFiles();
for (int j = 0; j < myarray.length; j++)
{
File path=myarray[j];
FileReader fr = new FileReader(path);
BufferedReader br = new BufferedReader(fr);
String s = "";
while (br.ready()) {
s += br.readLine() + "\n";
}
}
nice usage of java.io.FileFilter as seen on https://stackoverflow.com/a/286001/146745
File fl = new File(dir);
File[] files = fl.listFiles(new FileFilter() {
public boolean accept(File file) {
return file.isFile();
}
});
static File mainFolder = new File("Folder");
public static void main(String[] args) {
lf.getFiles(lf.mainFolder);
}
public void getFiles(File f) {
File files[];
if (f.isFile()) {
String name=f.getName();
} else {
files = f.listFiles();
for (int i = 0; i < files.length; i++) {
getFiles(files[i]);
}
}
}
I think this is good way to read all the files in a folder and sub folder's
private static void addfiles (File input,ArrayList<File> files)
{
if(input.isDirectory())
{
ArrayList <File> path = new ArrayList<File>(Arrays.asList(input.listFiles()));
for(int i=0 ; i<path.size();++i)
{
if(path.get(i).isDirectory())
{
addfiles(path.get(i),files);
}
if(path.get(i).isFile())
{
files.add(path.get(i));
}
}
}
if(input.isFile())
{
files.add(input);
}
}
Simple example that works with Java 1.7 to recursively list files in directories specified on the command-line:
import java.io.File;
public class List {
public static void main(String[] args) {
for (String f : args) {
listDir(f);
}
}
private static void listDir(String dir) {
File f = new File(dir);
File[] list = f.listFiles();
if (list == null) {
return;
}
for (File entry : list) {
System.out.println(entry.getName());
if (entry.isDirectory()) {
listDir(entry.getAbsolutePath());
}
}
}
}
While I do agree with Rich, Orian and the rest for using:
final File keysFileFolder = new File(<path>);
File[] fileslist = keysFileFolder.listFiles();
if(fileslist != null)
{
//Do your thing here...
}
for some reason all the examples here uses absolute path (i.e. all the way from root, or, say, drive letter (C:\) for windows..)
I'd like to add that it is possible to use relative path as-well.
So, if you're pwd (current directory/folder) is folder1 and you want to parse folder1/subfolder, you simply write (in the code above instead of ):
final File keysFileFolder = new File("subfolder");
Java 8 Files.walk(..) is good when you are soore it will not throw Avoid Java 8 Files.walk(..) termination cause of ( java.nio.file.AccessDeniedException ) .
Here is a safe solution , not though so elegant as Java 8Files.walk(..) :
int[] count = {0};
try {
Files.walkFileTree(Paths.get(dir.getPath()), new HashSet<FileVisitOption>(Arrays.asList(FileVisitOption.FOLLOW_LINKS)),
Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {
#Override
public FileVisitResult visitFile(Path file , BasicFileAttributes attrs) throws IOException {
System.out.printf("Visiting file %s\n", file);
++count[0];
return FileVisitResult.CONTINUE;
}
#Override
public FileVisitResult visitFileFailed(Path file , IOException e) throws IOException {
System.err.printf("Visiting failed for %s\n", file);
return FileVisitResult.SKIP_SUBTREE;
}
#Override
public FileVisitResult preVisitDirectory(Path dir , BasicFileAttributes attrs) throws IOException {
System.out.printf("About to visit directory %s\n", dir);
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
void getFiles(){
String dirPath = "E:/folder_name";
File dir = new File(dirPath);
String[] files = dir.list();
if (files.length == 0) {
System.out.println("The directory is empty");
} else {
for (String aFile : files) {
System.out.println(aFile);
}
}
}
package com;
import java.io.File;
/**
*
* #author ?Mukesh
*/
public class ListFiles {
static File mainFolder = new File("D:\\Movies");
public static void main(String[] args)
{
ListFiles lf = new ListFiles();
lf.getFiles(lf.mainFolder);
long fileSize = mainFolder.length();
System.out.println("mainFolder size in bytes is: " + fileSize);
System.out.println("File size in KB is : " + (double)fileSize/1024);
System.out.println("File size in MB is :" + (double)fileSize/(1024*1024));
}
public void getFiles(File f){
File files[];
if(f.isFile())
System.out.println(f.getAbsolutePath());
else{
files = f.listFiles();
for (int i = 0; i < files.length; i++) {
getFiles(files[i]);
}
}
}
}
Just to expand on the accepted answer I store the filenames to an ArrayList (instead of just dumping them to System.out.println) I created a helper class "MyFileUtils" so it could be imported by other projects:
class MyFileUtils {
public static void loadFilesForFolder(final File folder, List<String> fileList){
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
loadFilesForFolder(fileEntry, fileList);
} else {
fileList.add( fileEntry.getParent() + File.separator + fileEntry.getName() );
}
}
}
}
I added the full path to the file name.
You would use it like this:
import MyFileUtils;
List<String> fileList = new ArrayList<String>();
final File folder = new File("/home/you/Desktop");
MyFileUtils.loadFilesForFolder(folder, fileList);
// Dump file list values
for (String fileName : fileList){
System.out.println(fileName);
}
The ArrayList is passed by "value", but the value is used to point to the same ArrayList object living in the JVM Heap. In this way, each recursion call adds filenames to the same ArrayList (we are NOT creating a new ArrayList on each recursive call).
There are many good answers above, here's a different approach: In a maven project, everything you put in the resources folder is copied by default in the target/classes folder. To see what is available at runtime
ClassLoader contextClassLoader =
Thread.currentThread().getContextClassLoader();
URL resource = contextClassLoader.getResource("");
File file = new File(resource.toURI());
File[] files = file.listFiles();
for (File f : files) {
System.out.println(f.getName());
}
Now to get the files from a specific folder, let's say you have a folder called 'res' in your resources folder, just replace:
URL resource = contextClassLoader.getResource("res");
If you want to have access in your com.companyName package then:
contextClassLoader.getResource("com.companyName");
You can put the file path to argument and create a list with all the filepaths and not put it the list manually. Then use a for loop and a reader. Example for txt files:
public static void main(String[] args) throws IOException{
File[] files = new File(args[0].replace("\\", "\\\\")).listFiles(new FilenameFilter() { #Override public boolean accept(File dir, String name) { return name.endsWith(".txt"); } });
ArrayList<String> filedir = new ArrayList<String>();
String FILE_TEST = null;
for (i=0; i<files.length; i++){
filedir.add(files[i].toString());
CSV_FILE_TEST=filedir.get(i)
try(Reader testreader = Files.newBufferedReader(Paths.get(FILE_TEST));
){
//write your stuff
}}}
package com.commandline.folder;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class FolderReadingDemo {
public static void main(String[] args) {
String str = args[0];
final File folder = new File(str);
// listFilesForFolder(folder);
listFilesForFolder(str);
}
public static void listFilesForFolder(String str) {
try (Stream<Path> paths = Files.walk(Paths.get(str))) {
paths.filter(Files::isRegularFile).forEach(System.out::println);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void listFilesForFolder(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
System.out.println(fileEntry.getName());
}
}
}
}
We can use org.apache.commons.io.FileUtils, use listFiles() mehtod to read all the files in a given folder.
eg:
FileUtils.listFiles(directory, new String[] {"ext1", "ext2"}, true)
This read all the files in the given directory with given extensions, we can pass multiple extensions in the array and read recursively within the folder(true parameter).
public static List<File> files(String dirname) {
if (dirname == null) {
return Collections.emptyList();
}
File dir = new File(dirname);
if (!dir.exists()) {
return Collections.emptyList();
}
if (!dir.isDirectory()) {
return Collections.singletonList(file(dirname));
}
return Arrays.stream(Objects.requireNonNull(dir.listFiles()))
.collect(Collectors.toList());
}
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class AvoidNullExp {
public static void main(String[] args) {
List<File> fileList =new ArrayList<>();
final File folder = new File("g:/master");
new AvoidNullExp().listFilesForFolder(folder, fileList);
}
public void listFilesForFolder(final File folder,List<File> fileList) {
File[] filesInFolder = folder.listFiles();
if (filesInFolder != null) {
for (final File fileEntry : filesInFolder) {
if (fileEntry.isDirectory()) {
System.out.println("DIR : "+fileEntry.getName());
listFilesForFolder(fileEntry,fileList);
} else {
System.out.println("FILE : "+fileEntry.getName());
fileList.add(fileEntry);
}
}
}
}
}
list down files from Test folder present inside class path
import java.io.File;
import java.io.IOException;
public class Hello {
public static void main(final String[] args) throws IOException {
System.out.println("List down all the files present on the server directory");
File file1 = new File("/prog/FileTest/src/Test");
File[] files = file1.listFiles();
if (null != files) {
for (int fileIntList = 0; fileIntList < files.length; fileIntList++) {
String ss = files[fileIntList].toString();
if (null != ss && ss.length() > 0) {
System.out.println("File: " + (fileIntList + 1) + " :" + ss.substring(ss.lastIndexOf("\\") + 1, ss.length()));
}
}
}
}
}
/**
* Function to read all mp3 files from sdcard and store the details in an
* ArrayList
*/
public ArrayList<HashMap<String, String>> getPlayList()
{
ArrayList<HashMap<String, String>> songsList=new ArrayList<>();
File home = new File(MEDIA_PATH);
if (home.listFiles(new FileExtensionFilter()).length > 0) {
for (File file : home.listFiles(new FileExtensionFilter())) {
HashMap<String, String> song = new HashMap<String, String>();
song.put(
"songTitle",
file.getName().substring(0,
(file.getName().length() - 4)));
song.put("songPath", file.getPath());
// Adding each song to SongList
songsList.add(song);
}
}
// return songs list array
return songsList;
}
/**
* Class to filter files which have a .mp3 extension
* */
class FileExtensionFilter implements FilenameFilter
{
#Override
public boolean accept(File dir, String name) {
return (name.endsWith(".mp3") || name.endsWith(".MP3"));
}
}
You can filter any textfiles or any other extension ..just replace it with .MP3
This will Read Specified file extension files in given path(looks sub folders also)
public static Map<String,List<File>> getFileNames(String
dirName,Map<String,List<File>> filesContainer,final String fileExt){
String dirPath = dirName;
List<File>files = new ArrayList<>();
Map<String,List<File>> completeFiles = filesContainer;
if(completeFiles == null) {
completeFiles = new HashMap<>();
}
File file = new File(dirName);
FileFilter fileFilter = new FileFilter() {
#Override
public boolean accept(File file) {
boolean acceptFile = false;
if(file.isDirectory()) {
acceptFile = true;
}else if (file.getName().toLowerCase().endsWith(fileExt))
{
acceptFile = true;
}
return acceptFile;
}
};
for(File dirfile : file.listFiles(fileFilter)) {
if(dirfile.isFile() &&
dirfile.getName().toLowerCase().endsWith(fileExt)) {
files.add(dirfile);
}else if(dirfile.isDirectory()) {
if(!files.isEmpty()) {
completeFiles.put(dirPath, files);
}
getFileNames(dirfile.getAbsolutePath(),completeFiles,fileExt);
}
}
if(!files.isEmpty()) {
completeFiles.put(dirPath, files);
}
return completeFiles;
}
This will work fine:
private static void addfiles(File inputValVal, ArrayList<File> files)
{
if(inputVal.isDirectory())
{
ArrayList <File> path = new ArrayList<File>(Arrays.asList(inputVal.listFiles()));
for(int i=0; i<path.size(); ++i)
{
if(path.get(i).isDirectory())
{
addfiles(path.get(i),files);
}
if(path.get(i).isFile())
{
files.add(path.get(i));
}
}
/* Optional : if you need to have the counts of all the folders and files you can create 2 global arrays
and store the results of the above 2 if loops inside these arrays */
}
if(inputVal.isFile())
{
files.add(inputVal);
}
}

Categories