简体   繁体   English

java 写入文本文件

[英]java writing to a text file

I would like the following to be printed我想打印以下内容

test1测试1

test2测试2

test3测试3

test4测试4

But I can't seem to get the text to the next line.但我似乎无法将文本放到下一行。

Please help请帮忙

import java.io.*;

public class MainFrame {
    public static void main(String[] args) {
        try {
        BufferedWriter out = new BufferedWriter(new FileWriter("file.txt"));
            for (int i = 0; i < 4; i++) {
                out.write("test " + "\n");
            }
            out.close();
        } catch (IOException e) {}
    }
}

Try out.newLine();试试out.newLine();

So, it would be所以,这将是

for (int i = 0; i < 4; i++) {
    out.write("test " + "\n");
    out.newLine();
}

Source (Java API) 源代码(Java API)

You need have two \n\n to have a blank line.您需要有两个\n\n才能有一个空行。 Try尝试

out.write("test " + "\n\n");

In your case(with one \n ), it will break the current line and move to a new line(which is the next line) but the blank line will not come.在您的情况下(使用一个\n ),它将中断当前行并移至新行(即下一行),但不会出现空行。

The newline character can be depended on the platform , so it is better to get the new line character from the java system properties using换行符可以依赖于平台,所以最好使用 java 系统属性获取换行符

public static String newline = System.getProperty("line.separator");

If you want to generate text, it's probably easier to create a PrintWriter on top of that BufferedWriter, and use the methods in PrintWriter (like println) to do the writing.如果要生成文本,可能更容易在 BufferedWriter 之上创建一个 PrintWriter,并使用 PrintWriter 中的方法(如 println)进行写入。

The given answer - System.getProperty("line.separator") is good enough, but also try out.write("test " + "\r\n");给定的答案 - System.getProperty("line.separator")已经足够好了,但也试试out.write("test " + "\r\n"); it might work, as line break in some OS is \r\n and not \n它可能会起作用,因为某些操作系统中的换行符是\r\n而不是\n

Depending on what text editor you are opening the file with and what operating system you are using you might have to use "\r\n" instead of just "\n".根据您打开文件的文本编辑器以及您使用的操作系统,您可能必须使用“\r\n”,而不仅仅是“\n”。

Give it a try.试试看。

Considering you have an empty catch block, it could be that you're getting an exception and hiding it.考虑到您有一个空的 catch 块,可能是您遇到了异常并将其隐藏。 Remove the catch block and add throw IOException to your method definition so if you're getting an exception you can see it.删除catch块并将throw IOException添加到您的方法定义中,以便在遇到异常时可以看到它。

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

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