gpt4 book ai didi

Java 写入文件。使用循环

转载 作者:行者123 更新时间:2023-12-01 17:40:35 25 4
gpt4 key购买 nike

我有一个简单的应用程序,但它会删除一个文本文件(这只是练习),我只用了 3 天的 Java 时间。问题是,在运行程序之前不会出现任何错误,然后程序会抛出异常并停止。谢谢。这是异常(exception):

      java.io.IOException: Stream closed
at sun.nio.cs.StreamEncoder.ensureOpen(Unknown Source)
at sun.nio.cs.StreamEncoder.write(Unknown Source)
at sun.nio.cs.StreamEncoder.write(Unknown Source)
at java.io.OutputStreamWriter.write(Unknown Source)
at java.io.Writer.write(Unknown Source)
at test.main(test.java:18)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at
edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)

这就是代码。

import java.io.FileWriter;
import java.util.Random;
import java.io.IOException;
public class test {
public static void main(String[] args) throws IOException {

final String alphabet = "abcdefghigklmnopqrstuvwxyz";
final int N = alphabet.length();
Random r = new Random();

FileWriter file = new FileWriter("hello.txt");
String sb = " ";
for (int i = 0; i < 1;) {
sb += alphabet.charAt(r.nextInt(N));
System.out.println(sb);
int length = sb.length();
file.write(sb);
file.close();
if (length == 30) {
sb = " ";
}
}
}
}

最佳答案

问题是您正在关闭 FileWriter 并尝试再次使用它。

相反,在完成循环后关闭编写器:

try (FileWriter file = new FileWriter("hello.txt")) {
String sb = " ";
for (int i = 0; i < 1; i++) { // Note: added a i++
sb += alphabet.charAt(r.nextInt(N));
System.out.println(sb);
int length = sb.length();
file.write(sb);
// file.close(); <---- NOPE: don't do this
if (length == 30) {
sb = " ";
}
}
}

感谢Andrew用于发现 i++ 遗漏。

关于Java 写入文件。使用循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60955145/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com