I want to be able to list the files in the current directory. I've made something that should work but doesn't return all the file names.
File dir = new File("."); File[] filesList = dir.listFiles(); for (File file : filesList) { if (file.isFile()) { System.out.println(file.getName()); } }
It returns .classpath
, but I'm quite sure I have other java files inside this folder. Maybe the dot notation for current folder is incorrect?
You can use the DIR command by itself (just type “dir” at the Command Prompt) to list the files and folders in the current directory.
The dir command displays a list of files and subdirectories in a directory. With the /S option, it recurses subdirectories and lists their contents as well.
To determine the exact location of your current directory within the file system, go to a shell prompt and type the command pwd. This tells you that you are in the user sam's directory, which is in the /home directory. The command pwd stands for print working directory.
By default, the ls commands lists the contents of the working directory (i.e. the directory you are in). You can always find the directory you are in using the pwd command.
Try this,to retrieve all files inside folder and sub-folder
public static void main(String[]args) { File curDir = new File("."); getAllFiles(curDir); } private static void getAllFiles(File curDir) { File[] filesList = curDir.listFiles(); for(File f : filesList){ if(f.isDirectory()) getAllFiles(f); if(f.isFile()){ System.out.println(f.getName()); } } }
To retrieve files/folder only
public static void main(String[]args) { File curDir = new File("."); getAllFiles(curDir); } private static void getAllFiles(File curDir) { File[] filesList = curDir.listFiles(); for(File f : filesList){ if(f.isDirectory()) System.out.println(f.getName()); if(f.isFile()){ System.out.println(f.getName()); } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With