Java - Search for files in a directory - java

This is supposed to be simple, but I can't get it - "Write a program that searches for a particular file name in a given directory." I've found a few examples of a hardcoded filename and directory, but I need both the dir and file name to be as entered by the user.
public static void main(String[] args) {
String fileName = args[0]; // For the filename declaration
String directory;
boolean found;
File dir = new File(directory);
File[] matchingFiles = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String fileName) {
return true;
}
});
}

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

With **Java 8* there is an alternative that use streams and lambdas:
public static void recursiveFind(Path path, Consumer<Path> c) {
try (DirectoryStream<Path> newDirectoryStream = Files.newDirectoryStream(path)) {
StreamSupport.stream(newDirectoryStream.spliterator(), false)
.peek(p -> {
c.accept(p);
if (p.toFile()
.isDirectory()) {
recursiveFind(p, c);
}
})
.collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
}
So this will print all the files recursively:
recursiveFind(Paths.get("."), System.out::println);
And this will search for a file:
recursiveFind(Paths.get("."), p -> {
if (p.toFile().getName().toString().equals("src")) {
System.out.println(p);
}
});

This looks like a homework question, so I'll just give you a few pointers:
Try to give good distinctive variable names. Here you used "fileName" first for the directory, and then for the file. That is confusing, and won't help you solve the problem. Use different names for different things.
You're not using Scanner for anything, and it's not needed here, get rid of it.
Furthermore, the accept method should return a boolean value. Right now, you are trying to return a String. Boolean means that it should either return true or false. For example return a > 0; may return true or false, depending on the value of a. But return fileName; will just return the value of fileName, which is a String.

If you want to use a dynamic filename filter you can implement FilenameFilter and pass in the constructor the dynamic name.
Of course this implies taht you must instantiate every time the class (overhead), but it works
Example:
public class DynamicFileNameFilter implements FilenameFilter {
private String comparingname;
public DynamicFileNameFilter(String comparingName){
this.comparingname = comparingName;
}
#Override
public boolean accept(File dir, String name) {
File file = new File(name);
if (name.equals(comparingname) && !file.isDirectory())
return false;
else
return true;
}
}
then you use where you need:
FilenameFilter fileNameFilter = new DynamicFileNameFilter("thedynamicNameorpatternYouAreSearchinfor");
File[] matchingFiles = dir.listFiles(fileNameFilter);

I have used a different approach to search for a file using stack.. keeping in mind that there could be folders inside a folder. Though its not faster than windows search(and I was not expecting that though) but it definitely gives out correct result. Please modify the code as you wish to. This code was originally made to extract the file path of certain file extension :). Feel free to optimize.
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* #author Deepankar Sinha
*/
public class GetList {
public List<String> stack;
static List<String> lnkFile;
static List<String> progName;
int index=-1;
public static void main(String args[]) throws IOException
{
//var-- progFile:Location of the file to be search.
String progFile="C:\\";
GetList obj=new GetList();
String temp=progFile;
int i;
while(!"&%##".equals(temp))
{
File dir=new File(temp);
String[] directory=dir.list();
if(directory!=null){
for(String name: directory)
{
if(new File(temp+name).isDirectory())
obj.push(temp+name+"\\");
else
if(new File(temp+name).isFile())
{
try{
//".exe can be replaced with file name to be searched. Just exclude name.substring()... you know what to do.:)
if(".exe".equals(name.substring(name.lastIndexOf('.'), name.length())))
{
//obj.addFile(temp+name,name);
System.out.println(temp+name);
}
}catch(StringIndexOutOfBoundsException e)
{
//debug purpose
System.out.println("ERROR******"+temp+name);
}
}
}}
temp=obj.pop();
}
obj.display();
// for(int i=0;i<directory.length;i++)
// System.out.println(directory[i]);
}
public GetList() {
this.stack = new ArrayList<>();
this.lnkFile=new ArrayList<>();
this.progName=new ArrayList<>();
}
public void push(String dir)
{
index++;
//System.out.println("PUSH : "+dir+" "+index);
this.stack.add(index,dir);
}
public String pop()
{
String dir="";
if(index==-1)
return "&%##";
else
{
dir=this.stack.get(index);
//System.out.println("POP : "+dir+" "+index);
index--;
}
return dir;
}
public void addFile(String name,String name2)
{
lnkFile.add(name);
progName.add(name2);
}
public void display()
{
GetList.lnkFile.stream().forEach((lnkFile1) -> {
System.out.println(lnkFile1);
});
}
}

The Following code helps to search for a file in directory and open its location
import java.io.*;
import java.util.*;
import java.awt.Desktop;
public class Filesearch2 {
public static void main(String[] args)throws IOException {
Filesearch2 fs = new Filesearch2();
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();
fs.findFile(name,new File(directory));
}
public void findFile(String name,File file1)throws IOException
{
File[] list = file1.listFiles();
if(list!=null)
{
for(File file2 : list)
{
if (file2.isDirectory())
{
findFile(name,file2);
}
else if (name.equalsIgnoreCase(file2.getName()))
{
System.out.println("Found");
System.out.println("File found at : "+file2.getParentFile());
System.out.println("Path diectory: "+file2.getAbsolutePath());
String p1 = ""+file2.getParentFile();
File f2 = new File(p1);
Desktop.getDesktop().open(f2);
}
}
}
}
}

This method will recursively search thru each directory starting at the root, until the fileName is found, or all remaining results come back null.
public static String searchDirForFile(String dir, String fileName) {
File[] files = new File(dir).listFiles();
for(File f:files) {
if(f.isDirectory()) {
String loc = searchDirForFile(f.getPath(), fileName);
if(loc != null)
return loc;
}
if(f.getName().equals(fileName))
return f.getPath();
}
return null;
}

public class searchingFile
{
static String path;//defining(not initializing) these variables outside main
static String filename;//so that recursive function can access them
static int counter=0;//adding static so that can be accessed by static methods
public static void main(String[] args) //main methods begins
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the path : ");
path=sc.nextLine(); //storing path in path variable
System.out.println("Enter file name : ");
filename=sc.nextLine(); //storing filename in filename variable
searchfile(path);//calling our recursive function and passing path as argument
System.out.println("Number of locations file found at : "+counter);//Printing occurences
}
public static String searchfile(String path)//declaring recursive function having return
//type and argument both strings
{
File file=new File(path);//denoting the path
File[] filelist=file.listFiles();//storing all the files and directories in array
for (int i = 0; i < filelist.length; i++) //for loop for accessing all resources
{
if(filelist[i].getName().equals(filename))//if loop is true if resource name=filename
{
System.out.println("File is present at : "+filelist[i].getAbsolutePath());
//if loop is true,this will print it's location
counter++;//counter increments if file found
}
if(filelist[i].isDirectory())// if resource is a directory,we want to inside that folder
{
path=filelist[i].getAbsolutePath();//this is the path of the subfolder
searchfile(path);//this path is again passed into the searchfile function
//and this countinues untill we reach a file which has
//no sub directories
}
}
return path;// returning path variable as it is the return type and also
// because function needs path as argument.
}
}

I tried many ways to find the file type I wanted, and here are my results when done.
public static void main( String args[]){
final String dir2 = System.getProperty("user.name"); \\get user name
String path = "C:\\Users\\" + dir2;
digFile(new File(path)); \\ path is file start to dig
for (int i = 0; i < StringFile.size(); i++) {
System.out.println(StringFile.get(i));
}
}
private void digFile(File dir) {
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".mp4");
}
};
String[] children = dir.list(filter);
if (children == null) {
return;
} else {
for (int i = 0; i < children.length; i++) {
StringFile.add(dir+"\\"+children[i]);
}
}
File[] directories;
directories = dir.listFiles(new FileFilter() {
#Override
public boolean accept(File file) {
return file.isDirectory();
}
public boolean accept(File dir, String name) {
return !name.endsWith(".mp4");
}
});
if(directories!=null)
{
for (File directory : directories) {
digFile(directory);
}
}
}

Related

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");
}
}
}

display path of all files in the folder relative to the first file encountered in that folder

I am new to Java, I tried to practice some example but I am facing issue in the file handling topic.
Following is the example that what I am trying.
T1--> T2--> T3--> T4--> Gan--> q.txt
|
--> Lin-->Img-->s.png
|
--> p.txt
This is the folder structure.
And I want output in the following format.
p.txt
Lin/Img/s.png
Gen/q.txt
That means when the first file is getting in any directory, after that next file will be printed with the path from first file is got.
The above directory structure is not fixed. It may change.
Now following are code that I have did but I am not getting proper output:
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
class FileProgram {
private ArrayList<File> listOfDirectories = new ArrayList<File>();
private ArrayList<File> rawFiles = new ArrayList<File>();
private ArrayList<String> parentDir = new ArrayList<String>();
private ArrayList<String> filesToDisplay = new ArrayList<String>();
private Iterator i, listDir;
private boolean firstFile = false;
private String parents = "";
public void getDetails(File file) {
try {
if (file.exists()) {
File directoies[] = file.listFiles();
if (!rawFiles.isEmpty()) {
rawFiles.clear();
}
for (File f : directoies) {
rawFiles.add(f);
}
i = rawFiles.iterator();
while (i.hasNext()) {
File isFile = (File) i.next();
if (isFile.isFile()) {
displayFiles(isFile);
}
if (isFile.isDirectory()) {
listOfDirectories.add(isFile);
}
}
iterateInnerDirectories();
} else {
System.out.println("Invalid File Path");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
FileProgram ray = new FileProgram();
ray.getDetails(new File("D:\\Temp"));
}
private void iterateInnerDirectories() {
listDir = listOfDirectories.iterator();
while (listDir.hasNext()) {
File isFile = (File) listDir.next();
File f = isFile;
listOfDirectories.remove(isFile);
getDetails(isFile);
}
}
private void displayFiles(File file) {
if (firstFile == false) {
firstFile = true;
String rootPath = file.getParent();
rootPath = rootPath.replace(file.getName(), "");
parentDir.add(rootPath);
parents = file.getParentFile().getName();
System.out.println(file.getName());
filesToDisplay.add(file.getName());
} else {
String rootPath = file.getParent();
rootPath = rootPath.replace(file.getName(), "");
if (parentDir.contains(rootPath)) {
parents = file.getParentFile().getName();
System.out.println(file.getName());
filesToDisplay.add(file.getName());
} else {
System.out.println(file);
}
}
}
}
Please anybody can help me to get proper output that I have mentioned above.
Thanks in advance.
Unless you're using a Java prior to Java 7 I would strongly suggest to use Path.
You can walk a directory recursively using Files.walkFileTree().
Once you encounter a file (!Files.isDirectory()), you can get its parent with Path.getParent(). And you can print the relative path to this parent of all further file using Path.relativize().
Short, Simple Implementation
In this implementation I don't even use Files.isDirectory() because visitFile() is only called for files:
public static void printFiles(Path start) {
try {
Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
Path parent;
#Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attrs) throws IOException {
if (parent == null)
parent = file.getParent();
System.out.println(parent.relativize(file));
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
And this is how you call it:
printFiles(Paths.get("/path/to/T1"));

How to detect if a file(with any extension) exist in java

I am searching for a sound file in a folder and want to know if the sound file exist may it be .mp3,.mp4,etc.I just want to make sure that the filename(without extension) exists.
eg.File searching /home/user/desktop/sound/a
return found if any of a.mp3 or a.mp4 or a.txt etc. exist.
I tried this:
File f=new File(fileLocationWithExtension);
if(f.exist())
return true;
else return false;
But here I have to pass the extension also otherwise its returning false always
To anyone who come here,this is the best way I figured out
public static void main(String[] args) {
File directory=new File(your directory location);//here /home/user/desktop/sound/
final String name=yourFileName; //here a;
String[] myFiles = directory.list(new FilenameFilter() {
public boolean accept(File directory, String fileName) {
if(fileName.lastIndexOf(".")==-1) return false;
if((fileName.substring(0, fileName.lastIndexOf("."))).equals(name))
return true;
else return false;
}
});
if(myFiles.length()>0)
System.Out.println("the file Exist");
}
Disadvantage:It will continue on searching even if the file is found which I never intended in my question.Any suggestion is welcome
This code will do the trick..
public static void listFiles() {
File f = new File("C:/"); // use here your file directory path
String[] allFiles = f.list(new MyFilter ());
for (String filez:allFiles ) {
System.out.println(filez);
}
}
}
class MyFilter implements FilenameFilter {
#Override
//return true if find a file named "a",change this name according to your file name
public boolean accept(final File dir, final String name) {
return ((name.startsWith("a") && name.endsWith(".jpg"))|(name.startsWith("a") && name.endsWith(".txt"))|(name.startsWith("a") && name.endsWith(".mp3")|(name.startsWith("a") && name.endsWith(".mp4"))));
}
}
Above code will find list of files which has name a.
I used 4 extensions here to test(.jpg,.mp3,.mp4,.txt).If you need more just add them in boolean accept() method.
EDIT :
Here is the most simplified version of what OP wants.
public static void filelist()
{
File folder = new File("C:/");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles)
{
if (file.isFile())
{
String[] filename = file.getName().split("\\.(?=[^\\.]+$)"); //split filename from it's extension
if(filename[0].equalsIgnoreCase("a")) //matching defined filename
System.out.println("File exist: "+filename[0]+"."+filename[1]); // match occures.Apply any condition what you need
}
}
}
Output:
File exist: a.jpg //These files are in my C drive
File exist: a.png
File exist: a.rtf
File exist: a.txt
File exist: a.mp3
File exist: a.mp4
This code checks all the files of a path.It will split all filenames from their extensions.And last of all when a match occurs with defined filename then it will print that filename.
If you're looking for any file with name "a" regardless of the suffix, the glob that you're looking for is a{,.*}. The glob is the type of regular expression language used by shells and the Java API to match filenames. Since Java 7, Java has support for globs.
This Glob explained
{} introduces an alternative. The alternatives are separated with ,. Examples:
{foo,bar} matches the filenames foo and bar.
foo{1,2,3} matches the filenames foo1, foo2 and foo3.
foo{,bar} matches the filenames foo and foobar - an alternative can be empty.
foo{,.txt} matches the filenames foo and foo.txt.
* stands for any number of characters of any kind, including zero characters. Examples:
f* matches the filenames f, fa, faa, fb, fbb, fab, foo.txt - every file that's name starts with f.
The combination is possible. a{,.*} is the alternatives a and a.*, so it matches the filename a as well as every filename that starts with a., like a.txt.
A Java program that lists all files in the current directory which have "a" as their name regardless of the suffix looks like this:
import java.io.*;
import java.nio.file.*;
public class FileMatch {
public static void main(final String... args) throws IOException {
try (final DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get("."), "a{,.*}")) {
for (final Path entry : stream) {
System.out.println(entry);
}
}
}
}
or with Java 8:
import java.io.*;
import java.nio.file.*;
public class FileMatch {
public static void main(final String... args) throws IOException {
try (final DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get("."), "a{,.*}")) {
stream.forEach(System.out::println);
}
}
}
If you have the filename in a variable and you want to see whether it matches the given glob, you can use the FileSystem.getPathMatcher() method to obtain a PathMatcher that matches the glob, like this:
final FileSystem fileSystem = FileSystems.getDefault();
final PathMatcher pathMatcher = fileSystem.getPathMatcher("glob:a{,.*}");
final boolean matches = pathMatcher.matches(new File("a.txt").toPath());
You can try some thing like this
File folder = new File("D:\\DestFile");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if (file.isFile()) {
System.out.println("found ."+file.getName().substring(file.getName().lastIndexOf('.')+1));
}
}
Try this:
File parentDirToSearchIn = new File("D:\\DestFile");
String fileNameToSearch = "a";
if (parentDirToSearchIn != null && parentDirToSearchIn.isDirectory()) {
String[] childFileNames = parentDirToSearchIn.list();
for (int i = 0; i < childFileNames.length; i++) {
String childFileName = childFileNames[i];
//Get actual file name i.e without any extensions..
final int lastIndexOfDot = childFileName.lastIndexOf(".");
if(lastIndexOfDot>0){
childFileName = childFileName.substring(0,lastIndexOfDot );
if(fileNameToSearch.equalsIgnoreCase(childFileName)){
System.out.println(childFileName);
}
}//otherwise it could be a directory or file without any extension!
}
}
You could make use of the SE 7 DirectoryStream class :
public List<File> scan(File file) throws IOException {
Path path = file.toPath();
try (DirectoryStream<Path> paths = Files.newDirectoryStream(path.getParent(), new FileNameFilter(path))) {
return collectFilesWithName(paths);
}
}
private List<File> collectFilesWithName(DirectoryStream<Path>paths) {
List<File> results = new ArrayList<>();
for (Path candidate : paths) {
results.add(candidate.toFile());
}
return results;
}
private class FileNameFilter implements DirectoryStream.Filter<Path> {
final String fileName;
public FileNameFilter(Path path) {
fileName = path.getFileName().toString();
}
#Override
public boolean accept(Path entry) throws IOException {
return Files.isRegularFile(entry) && fileName.equals(fileNameWithoutExtension(entry));
}
private String fileNameWithoutExtension(Path candidate) {
String name = candidate.getFileName().toString();
int extensionIndex = name.lastIndexOf('.');
return extensionIndex < 0 ? name : name.substring(0, extensionIndex);
}
}
This will return files with any extension, or even without extension, as long as the base file name matches the given File, and is in the same directory.
The FileNameFilter class makes the stream return only the matches you're interested in.
public static boolean everExisted() {
File directory=new File(your directory location);//here /home/user/desktop/sound/
final String name=yourFileName; //here a;
String[] myFiles = directory.list(new FilenameFilter() {
public boolean accept(File directory, String fileName) {
if(fileName.lastIndexOf(".")==-1) return false;
if((fileName.substring(0, fileName.lastIndexOf("."))).equals(name))
return true;
else return false;
}
});
if(myFiles.length()>0)
return true;
}
}
When it returns, it will stop the method.
Try this one
FileLocationWithExtension = "nameofFile"+ ".*"

java: search file according to its name in directory and subdirectories

I need a to find file according to its name in directory tree. And then show a path to this file. I found something like this, but it search according extension. Could anybody help me how can I rework this code to my needs...thanks
public class filesFinder {
public static void main(String[] args) {
File root = new File("c:\\test");
try {
String[] extensions = {"txt"};
boolean recursive = true;
Collection files = FileUtils.listFiles(root, extensions, recursive);
for (Iterator iterator = files.iterator(); iterator.hasNext();) {
File file = (File) iterator.next();
System.out.println(file.getAbsolutePath());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class Test {
public static void main(String[] args) {
File root = new File("c:\\test");
String fileName = "a.txt";
try {
boolean recursive = true;
Collection files = FileUtils.listFiles(root, null, recursive);
for (Iterator iterator = files.iterator(); iterator.hasNext();) {
File file = (File) iterator.next();
if (file.getName().equals(fileName))
System.out.println(file.getAbsolutePath());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Recursive directory search in Java is pretty darn easy. The java.io.File class has a listFiles() method that gives all the File children of a directory; there's also an isDirectory() method you call on a File to determine whether you should recursively search through a particular child.
You can use FileFilter Like this.
public class MyFileNameFilter implements FilenameFilter {
#Override
public boolean accept(File arg0, String arg1) {
// TODO Auto-generated method stub
boolean result =false;
if(arg1.startsWith("KB24"))
result = true;
return result;
}
}
And call it like this
File f = new File("C:\\WINDOWS");
String [] files = null;
if(f.isDirectory()) {
files = f.list(new MyFileNameFilter());
}
for(String s: files) {
System.out.print(s);
System.out.print("\t");
}
Java 8 Lamda make this easier instead of using FileNameFilter, pass lambda expression
File[] filteredFiles = f.listFiles((file, name) ->name.endsWith(extn));
I don't really know what FileUtils does, but how about changing "txt" in extenstions to "yourfile.whatever"?
public static File find(String path, String fName) {
File f = new File(path);
if (fName.equalsIgnoreCase(f.getName())) return f;
if (f.isDirectory()) {
for (String aChild : f.list()) {
File ff = find(path + File.separator + aChild, fName);
if (ff != null) return ff;
}
}
return null;
}

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