如何将输出保存到txt文件

时间:2013-02-08 18:12:56

标签: java

快速问答

我有一个查找目录中所有文件的循环,我想要做的是在其中添加一行代码,将这些结果写入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 "";
    }

2 个答案:

答案 0 :(得分: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 "";
}

答案 1 :(得分: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 "";
}
相关问题