2013-02-08 79 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 ""; 
} 
相關問題