I am trying to make a program which will print all files in my current directory (but not the director开发者_开发技巧ies), 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.
精彩评论