2014-10-27 132 views
1

因此,我花了一段時間來修復調試中的所有錯誤,並運行我從我的簡介Java類寫出的程序。但現在它在第一次輸入後給我以下錯誤。Java io流關閉錯誤

Exception in thread "main" java.io.IOException: Stream closed 
at sun.nio.cs.StreamDecoder.ensureOpen(StreamDecoder.java:46) 
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:148) 
at java.io.InputStreamReader.read(InputStreamReader.java:184) 
at java.io.BufferedReader.fill(BufferedReader.java:161) 
at java.io.BufferedReader.readLine(BufferedReader.java:324) 
at java.io.BufferedReader.readLine(BufferedReader.java:389) 
at StatsDemo.main(StatsDemo.java:54) 

我根據評論和指示寫下了println下的所有內容。但我不確定有什麼問題。它應該要求輸入文件numbers.txt,但是在我輸入文件後,它給了我那個錯誤。

import java.text.DecimalFormat; 
import java.util.Scanner; 
import java.io.*; 

public class StatsDemo 
{ 
    public static void main(String [] args) throws IOException 
    { 
     double sum = 0; 
     int count = 0; 
     double mean = 0; 
     double stdDev = 0; 
     double difference; 

     DecimalFormat threeDecimals = new DecimalFormat("0.000"); 
     Scanner keyboard = new Scanner (System.in); 
     String filename; 

     System.out.println("This program calculates statistics" 
      + "on a file containing a series of numbers"); 
     System.out.print("Enter the file name: "); 
     filename = keyboard.nextLine(); 
+0

我必須給你自己的問題更多的考慮,但作爲一個附註,你應該從'main'方法中移除'throws IOException'。雖然它在技術上允許你避免try/catch,但你永遠不會有一個你控制調用'main'的實體,所以任何異常都將被處理,這不是一個好的編碼實踐。 – 2014-10-27 23:32:25

+0

您能否指出拋出異常的行? – TNT 2014-10-27 23:35:34

+0

可能重複的[java IO異常:流關閉](http://stackoverflow.com/questions/22900477/java-io-exception-stream-closed) – Chiseled 2014-10-27 23:39:06

回答

1

二回路你從閱讀:

線= in.readLine();

當您打開的流被稱爲in2。

即你正在閱讀錯誤和封閉的流。另外,作爲一種良好的習慣,您應該關閉最頂層的閱讀器,而不是內部,即您應該使用in.close()而不是file.close();

目的的同花順:

如果你看的PrintWriter源裏面你會看到它使用內部緩衝區:

public PrintWriter(File file, String csn) 
throws FileNotFoundException, UnsupportedEncodingException 
{ 
this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), csn)), 
    false); 
} 

,該緩衝區不會立即將輸出發送到底層輸出流。它將輸出保存在內存中直到刷新。通常,當輸出包含新行時,刷新會自動發生。否則,您需要手動刷新緩衝區以確保您的輸出實際上已被寫入。

+0

謝謝,我改變了他們,我不再流錯誤。但是我在result.txt文件中沒有看到任何結果。我究竟做錯了什麼? – James 2014-10-28 00:08:25

+1

嘗試在關閉前清除輸出流: outputFile.flush(); outputFile.close(); – Maxaon3000 2014-10-28 02:34:53

+0

非常感謝。它現在有效。我想知道沖洗的目的是什麼?僅供將來參考。再次感謝。 – James 2014-10-28 17:54:44