Java 写入文件。使用循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18380558/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 01:03:32  来源:igfitidea点击:

Java write to file. Using a loop

javastringfile

提问by Aras

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:

我有一个简单的应用程序,但它会破坏文本文件(这只是练习)我只有 3 天的时间使用 Java。问题是在您运行程序之前没有错误,然后它抛出异常并停止。谢谢你。这是例外:

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

采纳答案by Duncan Jones

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

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

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

Thanks to Andrewfor spotting the i++omission.

感谢安德鲁发现i++遗漏。

回答by Aniket Thakur

FileWriter file = new FileWriter("hello.txt");
    String sb =  " ";

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

You are initializing FileWriter once and closing it in the 1st iteration itself then trying to use it again in next iteration. Hence you are getting an Exception.

您正在初始化 FileWriter 一次并在第一次迭代中关闭它,然后尝试在下一次迭代中再次使用它。因此你得到一个例外。

I recommend put your for loop in try statement and close your FileWriter in finally statement. Hereis oracle tut on try-catch-finally construct.

我建议将你的 for 循环放在 try 语句中,并在 finally 语句中关闭你的 FileWriter。是关于 try-catch-finally 构造的 oracle tut。

Final code will go something like below

最终代码将如下所示

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

回答by awkwardChair

Only close your FileWriter stream once you are completely done using it.

只有在完全使用完 FileWriter 流后才关闭它。

Also, the write method for FileWriter does not include a method for only a String parameter. That might be the garbage you are getting when reading the file.

此外,FileWriter 的 write 方法不包括仅用于 String 参数的方法。这可能是您在读取文件时得到的垃圾。

回答by blackSmith

Your should close the FileWriter outside the for loop.

您应该在 for 循环之外关闭 FileWriter。

file.close();

Another problem with your code is that no increment is done on iin the loop. Thus it is a infinite loop and you program won't stop(after resolving the exception). Try something like:

您的代码的另一个问题是循环中的i没有进行任何增量。因此,这是一个无限循环,您的程序不会停止(解决异常后)。尝试类似:

for (int i = 0; i < 1; i++) 

or add a break condition within the body.

或在正文中添加中断条件。

回答by sheu

When you close the file as in the following line

当您按照以下行关闭文件时

 file.close()

it means you are done working with the file.

这意味着您已完成对文件的处理。

In your case you close the file in the loop which means the next iteration will throw an exception.

在您的情况下,您在循环中关闭文件,这意味着下一次迭代将引发异常。

Move the above mentioned code out of the loop.

将上述代码移出循环。

回答by max3d

Actual writing whilebeing in a loop will nottake place unless you call file.flush()method.

实际的写作,而在一个环路是不会,除非你调用文件发生。冲洗()方法。

FileWriter fileWriter = new FileWriter("hello.txt");
try {
    for (int i = 0; i < 10; i++) {
         fileWriter.write(line);
         fileWriter.flush();
    }
} finally {
     fileWriter.close();
}