Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to list the files in current directory?

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?

like image 422
Martynogea Avatar asked Mar 18 '13 16:03

Martynogea


People also ask

How do I list all files in a current directory in Windows?

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.

How do I list files and subfolders in the current folder?

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.

How do I list the current directory in Linux?

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.

What is the command to list of files and directory of current location?

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.


1 Answers

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());             }         }      } 
like image 83
Sachin Avatar answered Sep 18 '22 14:09

Sachin