Java写入文件.使用循环 [英] Java write to file. Using a loop

查看:491
本文介绍了Java写入文件.使用循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的应用程序,但是会丢弃文本文件(这只是练习),我使用Java才3天.问题是在运行程序之前没有错误,然后它会引发异常并停止.谢谢你. 例外:

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)

这是代码.

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并尝试再次使用它.

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();   <---- NOPE: don't do this
    if (length == 30) {
      sb = " ";
    }
  }
}

感谢 Andrew 发现了i++遗漏.

这篇关于Java写入文件.使用循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆