2013-02-08 71 views
-5

快速Q如何输出保存到一个txt文件

我有一个循环,发现在一个目录下的所有文件,我想要做的就是添加一行代码到它会写这些结果成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 ""; 
    } 
+3

使用BufferWriter? – PermGenError 2013-02-08 18:14:08

+1

http://docs.oracle.com/javase/tutorial/essential/io/file.html – 2013-02-08 18:15:06

回答

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 ""; 
} 
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 ""; 
} 
相关问题