Building an array of files in a directory
32,721
Solution 1
Looks like you are right on. I've put together your code bit more cleanly.
File[] fileList = new File(System.getProperty("user.home")).listFiles();
for (int i=0;i < fileList.length;i++) {
System.out.println(fileList[i]);
}
Solution 2
More or less yes, but you need to check that file is a file not a directory of course if you need only files names.
public static String[] fileNames(String directoryPath) {
File dir = new File(directoryPath);
Collection<String> files =new ArrayList<String>();
if(dir.isDirectory()){
File[] listFiles = dir.listFiles();
for(File file : listFiles){
if(file.isFile()) {
files.add(file.getName());
}
}
}
return files.toArray(new String[]{});
}
Solution 3
Yes that's how we get the list of file from local directory. Please note that the listFiles() will also include directories. So if you are interested only in files then you got to check isFile() on each file. If you are interested to get selective file user FileFilter.
Author by
Admin
Updated on February 29, 2020Comments
-
Admin about 4 years
How is this done in Java? I wish to create an array of fileNames to output in a program, the files will be the ones in my home directory.
So far I have :
File[] fileList = new File(user.home).listFiles()
Is this all I need ?
And then, to print out those files, can I just do :
int i = 0; while (fileList.getNext() != null) { System.out.println(filelist[i] i++ }
Thanks very much.