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


此异常反复出现,经过大量努力无法将其删除。

最佳答案

您继续关闭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();
    }
}

10-06 13:31