简体   繁体   中英

Saving a file List in a .txt

i trying to save this string with a file list into a file but it only saves the last one.. what is the problem here? :(

public void fileprinter() throws IOException{       
    File dir = new File("c:");
    String[] children = dir.list();
    if (children == null) {
        } else {
            for (int i=0; i<children.length; i++) {
                String filename = new StringBuffer().append(children[i]).toString();
                System.out.println(filename);
                Writer output;
                File file = new File("D:/file.txt");
                output = new BufferedWriter(new FileWriter(file));
                output.write(filename);
                output.close();
        }
    }
}

You keep overwriting the same file in the loop, so only the last line will "survive".

Open the BufferedWriter outside of the loop (once!) and close it when done.

An alternative would be to open in append mode, but even then don't reopen the same file in a loop over and over again.

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