2012-08-17 86 views
1

我是java的初學者,併爲postfix評估寫下面的問題。雖然該程序對控制檯IO正常工作。它在使用文件時有問題。我試圖在文件output00.txt中獲得該程序的答案,但該文件爲空。 這是代碼。我拋棄了對這個問題毫無幫助的方法。 input00.txt包含無法在java中執行文件IO

8 9 + 
7 6 - 
7 7 * 9 - 
+0

你是否在正確的地方尋找輸出文件?嘗試刪除並查看它是否被重新創建。代碼看起來很好,除了你不關閉輸出流。順便說一句這是一個功課? – aishwarya 2012-08-17 07:44:12

回答

6

你需要調用out.flush()來刷新你寫入文件的內容,或者調用out.close(),它應該自動刷新緩衝的內容。實際上,無論如何,您應該調用close(),因爲這是一種很好的做法,如果有某種方式可以退出while()循環。

+1

很好的答案,但是在關閉流時有點太放鬆。你必須調用'close()' - 不應該。因爲這是唯一有效的方法。 – 2012-08-17 07:53:11

+0

循環內部有一個catch塊,它似乎沒有做任何事情,但輸出錯誤,然後讓循環再次運行。你應該用catch來包裝循環,並用out.close()方法添加一個「finally」來確保清理。 – Dan 2012-08-17 12:18:15

2

public static void main(String[] args) throws Exception { 


    FileReader input = new FileReader("input00.txt"); 
     BufferedReader in = new BufferedReader(input) ; 
     FileWriter output = new FileWriter("output00.txt"); 
     BufferedWriter out = new BufferedWriter(output); 
     while (true) { 
      String lineReader = in.readLine(); 
      if (lineReader==null) { 
       break; 
      } 
      Stack<String> m_Stack = new Stack<String>(); 

      m_Stack.addAll(Arrays.asList(lineReader.trim().split("[ \t]+"))); 

      if (m_Stack.peek().equals("")){ 
       continue; 
      } 
      try { 
      double finVal = evaluateRPN(m_Stack); 
      if (!m_Stack.empty()) { 
       throw new Exception(); 
      } 
      out.write(finVal + "\n"); 
      } 
      catch (Exception e) {System.out.println("error");} 
     } 
     } 

文件您必須關閉流。試試out.close()

0

你可以嘗試在寫入語句後加入out.flush()。然後它會將緩衝區寫入文件。