Java 文件写入器 : To remove thread exception from code

标签 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)

这个异常反复出现,费了好大劲也没能去掉。

最佳答案

您不断关闭 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();
    }
}

关于Java 文件写入器 : To remove thread exception from code,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57973240/

相关文章:

java - 在 Java 中,为什么 FileWriter 抛出 IOException 而 FileOutputStream 抛出 FileNotFoundException 的原因完全相同

java - 以人类可读的格式将巨大的 ArrayList 写入文件

java - 编写器无法使用 Gson 处理 json 文件,代码执行后 json 文件为空

Java JSON - gson - 附加新数据,格式错误的 JSON

java - Maven 中 Unresolved 依赖关系

java - 使用 String.format() 处理日历与日期

java - 打印整个数据库列的方法

java - Recyclerview 不在嵌套的 ScrollView 内滚动

java - 如何在 Vaadin 中制作加载开始栏

java - 在java中将字符串数组写入csv文件的一列中