java循环写入文件,Java写入文件。使用循环

I have a simple application that yet would trash a text file (it's just practice) I'm only 3 days with Java yet. Problem is there are no errors until you run the program then it throws an exception and stops. Thank you.

This is the 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)

And this is the code.

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 = " ";

}

}

}

}

解决方案

The problem is that you are closing your FileWriter and trying to use it again.

Instead, close the writer after you've finished the loop:

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

if (length == 30) {

sb = " ";

}

}

}

Thanks to Andrew for spotting the i++ omission.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值