This question already has answers here:
How to read all files in a folder from Java?
(33 answers)
Closed 3 years ago.
I need to create a list with all names of the files in a folder.
For example, if I have:
000.jpg
012.jpg
013.jpg
I want to store them in a ArrayList with [000,012,013] as values.
What's the best way to do it in Java ?
PS: I'm on Mac OS X
You could do it like that:
File folder = new File("your/path");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
} else if (listOfFiles[i].isDirectory()) {
System.out.println("Directory " + listOfFiles[i].getName());
}
}
Do you want to only get JPEG files or all files?
Create a File object, passing the directory path to the constructor. Use the listFiles() to retrieve an array of File objects for each file in the directory, and then call the getName() method to get the filename.
List<String> results = new ArrayList<String>();
File[] files = new File("/path/to/the/directory").listFiles();
//If this pathname does not denote a directory, then listFiles() returns null.
for (File file : files) {
if (file.isFile()) {
results.add(file.getName());
}
}
Here's how to look in the documentation.
First, you're dealing with IO, so look in the java.io package.
There are two classes that look interesting: FileFilter and FileNameFilter. When I clicked on the first, it showed me that there was a a listFiles() method in the File class. And the documentation for that method says:
Returns an array of abstract pathnames
denoting the files in the directory
denoted by this abstract pathname.
Scrolling up in the File JavaDoc, I see the constructors. And that's really all I need to be able to create a File instance and call listFiles() on it. Scrolling still further, I can see some information about how files are named in different operating systems.
Related
I have a simple code to generate the temp files and store the some values(I don't want to store the files in normal storage area)
In future, I want to use that file and get the data from that file (its not a problem if the user manually delete the files).
But I don't want to delete the files automatically. when read this link, I get some information, generally temp files not deleted
when you explicitly call deleteOnExit() but when my JVM finish the work temp file deleted automatically.
//create a temp file
File temp = File.createTempFile("demo_", ".txt");
String path = temp.getParent();
//count the file which names starts with "demo"
File f = new File(path);
File[] matchingFiles = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith("demo") && name.endsWith(".txt");
}
});
// Print count array elements
System.out.println("Length : " + matchingFiles.length + " ");
Here I never call the deleteOnExit() (but file delete automtically)OR JVM automatically delete the file? By the way its deleted automatically if is it possible
to avoid deleting the file? or any other ways to do my requirement?
File.createTempFile only creates files with unique names, other than that they are just regular files. They are not deleted automatically. It is explained in File.createTempFile API: This method provides only part of a temporary-file facility. To arrange for a file created by this method to be deleted automatically, use the deleteOnExit method
Say I have a list of folders' names within a directory that has the path
C:\Users\Desktop\Application\('folder_names')
How would I delete certain folders within this directory and keep the ones I have stored in a list.
ie. I have a String List:
String[] deleteList = "folder 1, folder 2, folder 3";
and in the directory:
C:\Users\Desktop\Application\ I only want to delete folder 2
How might I do this using the String List instead of explicitly call out that folder?
So far I have:
UPDATED:
File[] deleteList = directory.listFiles(fileFilter);
for (File file : deleteList) {
if (file.isDirectory()) {
System.out.println(file.getPath());
if (file.getPath()
.equals("C:\\Users\\Desktop\\Application\\folder 2")) {
System.out.println("got folder");
FileUtils.deleteDirectory(file);
} else {
System.out.println("Didn't get it.");
}
}
}
Output
C:\Users\U201165\Desktop\Newfolder\Newfolder(2)
got folder
C:\Users\U201165\Desktop\Newfolder\Newfolder(3)
Didn't get it.
C:\Users\U201165\Desktop\Newfolder\Newfolder(4)
Didn't get it.
C:\Users\U201165\Desktop\Newfolder\Newfolder(5)
Didn't get it.
You are probably getting a relative path from the getPath(). To be sure that you are getting the absolute path from the File object, use:
if (file.getAbsolutePath().equals("C:\\Users\\Desktop\\Application\\folder2")) ...
instead of getPath().
Your System.out is showing the file object, but in your equals method you are using file.getPath(). Put file.getPath() in your system.out so you can see what you are actually comparing. The File object has a method like getExplicitPath() method. You might need to be using that instead of path. In some cases I think path just shows the file name, or the relative path not the expect one.
So I am writing a code that locates certain information on Protein databases. I know that a recursive folder search is the best possible way to locate these files, but I am very new to this language and have been told to write in Java (I normally do C++)
SO this being said, what method would i use to:
First: Locate the folder on desktop
Second: Open each folder and that folders subfolders
Third: Locate files that end with the ".dat" type (because these are the only files that have stored the Protein information
Thanks for any and all help you can provide
java.io.File is "An abstract representation of file and directory pathnames"
File.listFiles provides a listing of all the files contained within the directory (if the File object represents a directory)
File.listFiles(FileFilter) provides you with the ability to filter a file list based on your needs
So, with that information...
You would specify a path location with something like...
File parent = new File("C:/path/to/where/you/want");
You can check that the File is a directory with...
if (parent.isDirectory()) {
// Take action of the directory
}
You can list the contents of the directory by...
File[] children = parent.listFiles();
// This will return null if the path does not exist it is not a directory...
You can filter the list in a similar way...
File[] children = parent.listFiles(new FileFilter() {
public boolean accept(File file) {
return file.isDirectory() || file.getName().toLowerCase().endsWith(".dat");
}
});
// This will return all the files that are directories or whose file name ends
// with ".dat" (*.dat)
Other useful methods would include (but not limited to)
File.exists to test that the file actually exists
File.isFile, basically instead of saying !File.isDirectory()
File.getName(), returns the name of the file, excluding it's path
File.getPath() returns the path and name of the file. This can be relative, so be careful, see File.getAbsolutePath and File.getCanonicalPath to resolve this.
File.getParentFile which gives you access to the parent folder
Something like this would do the trick:
public static void searchForDatFiles(File root, List<File> datOnly) {
if(root == null || datOnly == null) return; //just for safety
if(root.isDirectory()) {
for(File file : root.listFiles()) {
searchForDatFiles(file, datOnly);
}
} else if(root.isFile() && root.getName().endsWith(".dat")) {
datOnly.add(root);
}
}
After this method returns, the List<File> passed to it will be filled with the .dat files of your directory, and all subdirectories (if i'm not mistaken).
You should have a look at the Java File APIs. In particular you should look at the listFiles method and write FileFilter that selects directories and, of course, the files you're interested into.
A method that will return you all the files matching your criteria (Given that you implement the FileFilter) is this:
List<File> searchForFile(File rootDirectory, FileFilter filter){
List<File> results = new ArrayList<File>();
for(File currentItem : rootDirectory.listFiles(filter){
if(currentItem.isDirectory()){
results.addAll(searchForFile(currentItem), filter)
}
else{
results.add(currentItem);
}
}
return results;
}
use recursive foldr search and use function endsWith() to find the .bat file then you can use any String function to locate your requires information.
In Android, assuming that I have files in "/data/data/package.name/", without knowing the names or how many files exist, what is the best way to retrieve/iterate them all?
Also, the name is numerical only.
It looks like you want to list all of the files in the directory, and (possibly) recurse if a file is a directory.
You can find how to do this at the answer to this question.
Copy-pasted:
File f = new File("/data/data/package.name/");
File[] files = f.listFiles();
for (File inFile : files) {
if (inFile.isDirectory()) {
// is directory; recurse?
} else {
doLogicFor(inFile);
}
}
I am trying to make a program which will print all files in my current directory (but not the directories), and at the moment what I have is printing all files and directories in my home directory. How can I change this ?
My code at the moment :
File[] fileList = new File(System.getProperty("user.home")).listFiles();
Also, how can I print the details of these files as well ? I would like the file size, permissions, anything I can get, so as to make my program the equivalent to an ls -a in unix.
Can someone please help me with this as I cannot find the pertinent Java functions anywhere?
Thanks a lot!
You can use a FileFilter to get rid of dirs
File[] files = new File(System.getProperty("user.home")).listFiles(new FileFilter() {
public boolean accept(File file) {
return !file.isDirectory();
}
});
You can get the size of file with file.length()
You can get the files by using a FileFilter, like so:
File dir = new File("/path/to/directory");
FileFilter fileFilter = new FileFilter() {
public boolean accept(File file) {
return file.isFile();
}
};
File[] files = dir.listFiles(fileFilter);
for (File file : files) {
System.out.println("File: " + file);
}
Your question doesn't make sense.
You ask in your coment to Bozho to print a list of files in the current directory, but specifically asks for a list of files in "user.home", which is your home directory.
If you don't want to list the files in your home directory, change your code to ask for files from somewhere else.
Loop the array and print only those which have isFile() true (or isDirectory() false). The current directory is simpyl new File("")
All details you can obtain by calling the respective methods, like canRead(), canWrite(), length(), etc. Check the documentation for more
Get the current directory by initializing a file object for it and then using the listFiles() method from that object. Then loop over the resulting list and test each file with the File.isFile() method:
File cwd = new File(".");
File[] fileList = cwd.listFiles()
for (File aFile : fileList) {
if (aFile.isFile()) {
System.out.println(aFile);
}
}
You can use the canExecute(), canRead(), and canWrite() methods to find out if your program can do those things. As noted in another answer, length() will give you the size.