Getting file details and not printing directory help - java

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.

Related

Deleting certain folders within a directory java

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.

Adding files to a file[] statement in java

Hello members of stackoverflow
I need some help with adding files from a directory to a bunch of files (File[])
So basically i want to add all the files in a directory to the following group of files:
File[] contents = {};
The user of my application will select a directory and i want that directories contents to be added to the above group of files ('contents I'm not sure how this is done because it doesn't have a simple 'add' method like an ArrayList/List does.
Any help with this would be greatly appreciated.
Thanks.
Use File.listFiles():
File dir = new File("/somedir");
File[] files = dir.listFiles();
try
{
File folder = new File(FOLDER_NAME);
File[] contents = folder.listFiles();
}
catch(Exception e)
{
System.out.println("[Error] Folder not Found");
}

Recursive method to search through folder tree and find specific file types

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.

How to retrieve every file in the Internal Storage?

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

Getting the filenames of all files in a folder [duplicate]

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.

Categories

Resources