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

Java FileWriter: To remove thread exception from code

使用 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();
    }
}

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));
    }
}