简体   繁体   English

如何在Java中将多个行写入文本文件?

[英]How do I write multiple lines to a text file in Java?

So I want to create and write to a file in Java. 所以我想用Java创建并写入文件。 I know how to do it with one line, but I'm wondering how I write multiple lines to a single file. 我知道如何用一行来完成,但是我想知道如何将多个行写到一个文件中。

import java.io.FileWriter;
import java.io.BufferedWriter;

public class WritingToAFile {

public static void main(String[] args) {

   try{ 
   FileWriter fstream = new FileWriter ("P:/Computer Science/greeting.txt");
   BufferedWriter info = new BufferedWriter(fstream);

   for(int i = 1; i < 6; i++){
       info.write("Hello");
       info.newLine();
       info.write("Bonjour");
       info.newLine();
       info.write("Guten tag");
       info.newLine();
       info.write("Aloha");
       info.newLine();
       info.write("Nihao");
       info.close();
       }catch(Exception e){
          System.out.println("A write error has occurred");
    }   
  }
}

I know it's wrong right now, but I'm not sure what I did wrong. 我知道现在错了,但是我不确定自己做错了什么。 Help would be much appreciated! 帮助将不胜感激! I'm only a beginner so I'm really lost. 我只是一个初学者,所以我真的迷路了。

You're closing you're file each iteration - info.close(); 您正在关闭每次迭代的文件info.close(); - that's the reason you'll have the exception. -这就是您会有例外的原因。 You need to close the file once you'll finish to write to it. 完成写入后,您需要关闭文件。

There is nothing wrong with newLine(); newLine();没有错newLine(); approach. 方法。 However you can make it shorter using new line character. 但是,您可以使用换行符将其缩短。

"\\n" - is a new line separator for Unix-based systems. "\\n" -是基于Unix的系统的新行分隔符。

"\\r\\n" - is a new line separator for Windows systems. "\\r\\n" -是Windows系统的新行分隔符。

"%n" is a platform independent new line separator. "%n"是独立于平台的换行符。

for(int i = 1; i < 6; i++) {
    info.write(String.format("Hello%n"));
}
info.close();

The second issue is here that you're not closing FileWriter itself. 第二个问题是您没有关闭FileWriter本身。

If you're using Java 7+, I would recommend to do it using try-with-resources to to get rid of finally blocks: 如果您使用的是Java 7+,我建议您使用try-with-resources来实现,以摆脱finally块:

public class Main {

    public static void main(String[] args) {
        try (FileWriter fstream = new FileWriter("greeting.txt");
             BufferedWriter info = new BufferedWriter(fstream)) {
            for (int i = 1; i < 6; i++) {
                info.write(String.format("Hello%n"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

File output: 文件输出:

Hello
Hello
Hello
Hello
Hello

UPDATE: 更新:

All the input-output operations require to deal with streams, channels, file descriptors (like FileWriter , BufferedWriter in your particular case). 所有输入输出操作都需要处理流,通道,文件描述符(在您的特定情况下,如FileWriterBufferedWriter )。 These streams should be closed carefully to release system resources. 这些流应仔细关闭以释放系统资源。 Failing to do so may lead to resources leak. 否则可能会导致资源泄漏。 Despite you closed info you forgot to close fstream in the code. 尽管您关闭了info您忘记了在代码中关闭fstream

When you use the try-with-resources statement correctly, then you will never have to close streams explicitly. 当正确使用try-with-resources语句时,您将不必显式关闭流。 The try-with-resources statement ensures that each resource is closed at the end of the statement. try-with-resources语句可确保在语句末尾关闭每个资源。

You have almost got it right, in fact, it's nothing to do with info.newLine(); 几乎完全正确,实际上,它与info.newLine();无关info.newLine(); but rather the syntax of your code. 而是代码的语法。

Your catch is actually after your for loop, and not connected to the try . 您的catch实际上是在for循环之后,并且未连接到try

And you also close the stream in the for loop, instead of after it has completed (this would cause an IOException ). 而且,您还可以在for循环中关闭流,而不是在流完成之后关闭它(这将导致IOException )。

Sample: 样品:

try {
    FileWriter fstream = new FileWriter("P:/Computer Science/greeting.txt");
    BufferedWriter info = new BufferedWriter(fstream);
    for (int i = 1; i < 6; i++) {
        info.write("Hello");
        info.newLine();
        info.write("Bonjour");
        info.newLine();
        info.write("Guten tag");
        info.newLine();
        info.write("Aloha");
        info.newLine();
        info.write("Nihao");
    }
    info.close();
} catch (Exception e) {
    System.out.println("A write error has occurred");
}

just add \\n or \\r\\n platform new line character based on system at the end of string in write method 只需在write方法的字符串末尾基于系统添加\\n\\r\\n平台新行字符

try{
    for(int i = 1; i < 6; i++){
           info.write("Hello\n");
           info.write("Bonjour\n");
           ...

           }
    }
    catch (Exception e) {
    System.out.println("A write error has occurred");
}
finally{
    info.close();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM