2015-11-16 61 views
-1
import java.io.FileReader; 
import java.io.FileWriter; 
import java.io.BufferedReader; 
import java.io.BufferedWriter; 
import java.io.FileNotFoundException; 
import java.util.Scanner; 
public class Letter_Counter 
{ 
    public static void main(String[] args) throws Exception 
    { 
     String filename = ""; 
    String outFile = ""; 
    FileReader fr1 = null; 
    FileWriter fw1 = null; 
    BufferedReader br1 = null; 
    BufferedWriter bw1 = null; 
    Scanner myScan = new Scanner(System.in); 
    boolean isValid = true; 
    int[] count = new int[56]; 

    do 
    { 
     try 
     { 
      isValid = true; 
      System.out.print("Input a file name: "); 
      filename = myScan.nextLine(); 
      fr1 = new FileReader(filename); 
      br1 = new BufferedReader(fr1); 
     } 
     catch(FileNotFoundException e) 
     { 
      System.out.println("Invalid filenme given. Input another."); 
      isValid = false; 
     } 
    }while(!isValid); 

    do 
    { 
     try 
     { 
      isValid = true; 
      System.out.print("Input an out file name: "); 
      outFile = myScan.nextLine(); 
      fw1 = new FileWriter(outFile); 
      bw1 = new BufferedWriter(fw1); 
     } 
     catch(Exception e) 
     { 
      System.err.println("Error: "+e.getMessage()); 
      isValid = false; 
     } 
    }while(!isValid); 

    System.out.println("Reading from "+filename); 

    try 
    { 
     String line; 

     while((line = br1.readLine()) != null) 
     { 
      System.out.println(line); 
      for(int i=0; i<line.length(); i++) 
      { 
       for(int j=97; j<123; j++) 
       { 
        if((int)line.charAt(i)==j) 
        { 
         count[j-97]++; 
        } 
       } 
       for(int k=65; k<91; k++) 
       { 
        if((int)line.charAt(i)==k) 
        { 
         count[k-38]++; 
        } 
       } 
      } 
     } 
    } 
    catch(Exception e) 
    { 
     System.err.println("Error: "+e.getMessage()); 
    } 

    try 
    { 
     char c = 'A'; 
     for(int i=26; i<52; i++) 
     { 
      bw1.write(c+"="+count[i]); 
      System.out.println(c+"="+count[i]); 
      bw1.newLine(); 
      c++; 
     } 
     c = 'a'; 
     for(int i=0; i<26; i++) 
     { 
      bw1.write(c+"="+count[i]); 
      System.out.println(c+"="+count[i]); 
      bw1.newLine(); 
      c++; 
     } 
    } 
    catch(Exception e) 
    { 
     System.err.println(e.getMessage()); 
    } 

    System.out.println("Results stored in "+outFile); 
} 
} 

很抱歉的壞壓痕.. 它打印精細到控制檯,但不會寫什麼我使用了錯誤的語法寫 ,因爲它不拋出任何異常或者文件.. 任何與所有的幫助表示讚賞這個程序爲什麼不寫任何內容到輸出文件?

回答

1

沒關係..想通了..我只是忘了關緩衝..

0

你沒忘了在年底前完成的BufferedWriter?

bw1.close(); 
0

只是輸入/輸出文件名的路徑名正確。 並在這樣的belwo地方關閉fw1。

System.out.println("Results stored in "+outFile); 
    fw1.close(); 
相關問題