Java FileWriter:从代码中删除线程异常

使用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)

这个异常一次又一次的出现,经过一番努力还是无法消除。


喵喵时光机
浏览 111回答 2
2回答

BIG阳

您不断关闭 for 循环内的流。将其移到大括号之外,如下所示:import java.io.*;class Wx {&nbsp; &nbsp; public static void main(String args[]) throws IOException {&nbsp; &nbsp; &nbsp; &nbsp; String str="Oh ho ho ho oh ho ho ho oh ho ho ho ohho ishq tera tadpaaweee";&nbsp; &nbsp; &nbsp; &nbsp; FileWriter f=new FileWriter("text");&nbsp; &nbsp; &nbsp; &nbsp; for(int i=0;i<str.length();i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; f.write(str.charAt(i));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; f.close();&nbsp; &nbsp; }}

哔哔one

FileWriter实现Closeable(JDK 1.5) ,因此您还可以使用显try-with-resources式依赖于closing()流的语句:try (FileWriter f = new FileWriter("text")) {&nbsp; &nbsp; for (int i = 0; i < str.length(); i++) {&nbsp; &nbsp; &nbsp; &nbsp; f.write(str.charAt(i));&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java