亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Java FileWriter:從代碼中刪除線程異常

Java FileWriter:從代碼中刪除線程異常

喵喵時光機 2023-08-04 19:21:32
使用FileWriter創建文本文件的程序。import java.io.FileWriter;import java.io.IOException;class Wx {    public static void main(String args[]) throws IOException {        String str = "Oh ho ho ho oh ho ho ho oh ho ho ho ohho ishq tera tadpaaweee ";        FileWriter f = new FileWriter("text");        for (int i = 0; i < str.length(); i++) {            f.write(str.charAt(i));            f.close();        }    }}這個異常即將到來:Exception in thread "main" java.io.IOException: Stream closed        at sun.nio.cs.StreamEncoder.ensureOpen(StreamEncoder.java:26)        at sun.nio.cs.StreamEncoder.write(StreamEncoder.java:99)        at sun.nio.cs.StreamEncoder.write(StreamEncoder.java:94)        at java.io.OutputStreamWriter.write(OutputStreamWriter.java:177)        at Wx.main(Wx.java:10)這個異常一次又一次的出現,經過一番努力還是無法消除。
查看完整描述

2 回答

?
BIG陽

TA貢獻1859條經驗 獲得超6個贊

您不斷關閉 for 循環內的流。將其移到大括號之外,如下所示:


import java.io.*;


class Wx {

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

        String str="Oh ho ho ho oh ho ho ho oh ho ho ho ohho ishq tera tadpaaweee";

        FileWriter f=new FileWriter("text");

        for(int i=0;i<str.length();i++) {

            f.write(str.charAt(i));

        }

        f.close();

    }

}


查看完整回答
反對 回復 2023-08-04
?
嗶嗶one

TA貢獻1854條經驗 獲得超8個贊

FileWriter實現Closeable(JDK 1.5) ,因此您還可以使用顯try-with-resources式依賴于closing()流的語句:


try (FileWriter f = new FileWriter("text")) {

    for (int i = 0; i < str.length(); i++) {

        f.write(str.charAt(i));

    }

}


查看完整回答
反對 回復 2023-08-04
  • 2 回答
  • 0 關注
  • 141 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號