0

I'm not a really good Java programmer and I need to know how I can print out all the files in a single folder. See the code below:

for(int i=0;i<folder.number_of_files;i++){
System.out.println(filename[i]);
}

Thanks for your time

3 Answers 3

8

Easiest way would be to use File#listFiles. And if you're using Java 7, see this for changes to the file I/O library. For instance,

File folder = ...;
for(File f : folder.listFiles())
{
    System.out.println(f.getName());
}

Note that this will not grab the contents of any sub-folders within the folder directory.

Sign up to request clarification or add additional context in comments.

Comments

4
 File file = new File("C:\\");  
 File[] files = file.listFiles();  
 for (File f:files)  
 {  
     System.out.println(f.getAbsolutePath());  
 }  

listFiles() has more options. see the documentation here

Comments

3

If you also want to check subfolders below example runs a recursive and check all files under Desktop and its subfolders and writes into a list.

private static String lvl = "";
    static BufferedWriter bw;
    private static File source = new File("C:\\Users\\"+System.getProperty("user.name")+"\\Desktop\\New folder\\myTest.txt");

    public static void main(String[] args) throws IOException {




        bw = new BufferedWriter(new FileWriter(source));

        checkFiles(new File("C:\\Users\\"+System.getProperty("user.name")+"\\Desktop"), 0);


        bw.flush();
        bw.close();
        lvl = null;

    }
    static void checkFiles(File file, int level) throws IOException{

        if(!file.exists()){

            return;
        }

        for(String s:file.list()){

            if(new File(file.getPath() + "\\" +  s).isDirectory()){

                bw.newLine();
                bw.write(lvl + "Directory: " + s);

                lvl += " ";

                checkFiles(new File(file.getPath() + "\\" +  s), level+1);

            }else{

                bw.newLine();
                bw.write(lvl + "File: " + s);

            }
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.