-5

快问

我有一个循环,可以找到目录中的所有文件,我想做的是在其中添加一行代码,将这些结果写入 txt 文件,我将如何最好地做到这一点

当前代码:

public String FilesInFolder() {
        // Will list all files in the directory, want to create a feature on the page that can display this to the user

        String path = NewDestination;
        System.out.println("Starting searching files in directory"); // making sure it is called
        String files;
        File folder = new File(path);
        File[] listOfFiles = folder.listFiles();

        for (int i = 0; i < listOfFiles.length; i++) {

            if (listOfFiles[i].isFile()) {
                files = listOfFiles[i].getName();
                System.out.println(files);
            }
        }
        return "";
    }
4

2 回答 2

1

使用FileWritterBufferedWriter

public String FilesInFolder() {
    // Will list all files in the directory, want to create a feature on the page that can display this to the user

    String path = NewDestination;
    System.out.println("Starting searching files in directory"); // making sure it is called
    String files;
    File folder = new File(path);
    File[] listOfFiles = folder.listFiles();


    File file = new File("output.txt");

    // if file doesnt exists, then create it
    if (!file.exists()) {
        file.createNewFile();
    }
    FileWriter fw = new FileWriter(file.getAbsoluteFile());
    BufferedWriter bw = new BufferedWriter(fw);

    for (int i = 0; i < listOfFiles.length; i++) {

        if (listOfFiles[i].isFile()) {
            files = listOfFiles[i].getName();
            System.out.println(files);
            bw.write(files);
        }
    }

    bw.close();
    return "";
}
于 2013-02-08T18:19:19.150 回答
1

您可以一起使用FileWriterStringWriter

 public String FilesInFolder() throws IOException {
    FileWriter fw = new FileWriter("file.txt");
    StringWriter sw = new StringWriter();

    // Will list all files in the directory, want to create a feature on the page that can display this to the user

    String path = NewDestination;
    System.out.println("Starting searching files in directory"); // making sure it is called
    String files;
    File folder = new File(path);
    File[] listOfFiles = folder.listFiles();

    for (int i = 0; i < listOfFiles.length; i++) {

        if (listOfFiles[i].isFile()) {
            files = listOfFiles[i].getName();
            sw.write(files);
            System.out.println(files);
        }
    }
    fw.write(sw.toString());
    fw.close();
    return "";
}
于 2013-02-08T18:19:57.310 回答