简体   繁体   中英

what's wrong with this program to list all the files?

I am a beginner, want to know what's wrong with the code below. I ran the code, but it can only list the files in one of the subfolders in C:\\JavaData

import java.io.*;
import java.util.*;

class fileNames
{
    public static void main(String[] args) throws IOException
    {
        File dir = new File("C:\\JavaData");
        File desFile = new File(dir,"list.txt");
        writeFileNames(dir,desFile);
    }
    public static void writeFileNames(File dir,File desFile) throws IOException
    {
        BufferedWriter bfw = new BufferedWriter(new FileWriter(desFile));
        File[] files = dir.listFiles();


        for(File f : files)
        {
            if(f.isDirectory())
            {
                writeFileNames(f,desFile);
            }
            else
            {
                bfw.write(f.getAbsolutePath());
                bfw.newLine();
                bfw.flush();
            }

        }
        bfw.close();
    }
}

Pass the Writer (not the File desFile), you are opening the file to write in the first invocation (when you recurse, you still have it open). Also, I'd use a try-with-resources instead of an explicit close() . Like,

public static void main(String[] args) throws IOException {
    File dir = new File("C:\\JavaData");
    File desFile = new File(dir, "list.txt");
    try (BufferedWriter bfw = new BufferedWriter(new FileWriter(desFile))) {
        writeFileNames(dir, bfw);
    }
}

public static void writeFileNames(File dir, BufferedWriter bfw) throws IOException {
    File[] files = dir.listFiles();
    for (File f : files) {
        if (f.isDirectory()) {
            writeFileNames(f, bfw);
        } else {
            bfw.write(f.getAbsolutePath());
            bfw.newLine();
            bfw.flush();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM