2015-11-04 126 views
0

我試圖讓「測試」或任何要打印出來的文件名爲doctor.txtFileWriter不寫入.txt文件

每當我運行該程序,它只是出現在文件上的空白。另外,您是否必須事先在文件夾中創建.txt文件,或者是否自動爲您創建文件?

這裏是我的代碼:

import java.util.Scanner; 
import java.io.File; 
import java.io.IOException; 
import java.io.FileWriter; 

public class Vowels { 

    public static void main(String [] args) { 
     try { 
      int countA = 0; 
      int countE = 0; 
      int countI = 0; 
      int countO = 0; 
      int countU = 0; 

     Scanner in = new Scanner(new File("poetry.txt")); 
     String poetry = ""; 

     while(in.hasNext()){ 
      poetry = in.nextLine(); 
      poetry = poetry.replaceAll(" ", "~"); 
      System.out.println(poetry); 

      for(int v = 0; v < poetry.length(); v++) { 
       if(poetry.charAt(v) == 'a') { 
        countA++; 
       } 
       if(poetry.charAt(v) == 'e') { 
        countE++; 
       } 
       if(poetry.charAt(v) == 'i') { 
        countI++; 
       } 
       if(poetry.charAt(v) == 'o') { 
        countO++; 
       } 
       if(poetry.charAt(v) == 'u') { 
        countU++; 
       } 
      } 

     } 
     System.out.println(); 
     System.out.println("The number of 'A's is: " + countA); 
     System.out.println("The number of 'E's is: " + countE); 
     System.out.println("The number of 'I's is: " + countI); 
     System.out.println("The number of 'O's is: " + countO); 
     System.out.println("The number of 'U's is: " + countU); 
     FileWriter doctor = new FileWriter("doctor.txt"); 
     doctor.write("test"); 
    } 
    catch(IOException i) { 
     System.out.println("Error: " + i.getMessage()); 
    } 
} 
+3

你沒有關閉或沖洗'FileWriter' –

回答

3

doctor.close();doctor.write("test");後。

+2

讓我們關閉醫生:)我不知道爲什麼和誰downvoted這傢伙的答案?然而,我同意@Subhrajyoti Majumder,但它只是一個評論,應該有答案以及... @ eclideria它的好提供更多的解釋,爲什麼你要關閉博士:)我upvoting –