gpt4 book ai didi

java - 行尾,FileWriter\n

转载 作者:行者123 更新时间:2023-12-01 15:25:01 28 4
gpt4 key购买 nike

我正在尝试将换行符 append 到已存在的文件中,但我尝试过的所有命令都导致仅 append 到第一行。我希望文件中的输出看起来像

行1

行2

 private void addToFavToFile(String site){
BufferedWriter writer = null;
File root = Environment.getExternalStorageDirectory();
try{
writer = new BufferedWriter(new FileWriter(Environment.getExternalStorageDirectory()+"/test2.txt",true));
writer.write("ROW1");
writer.newLine();
writer.write("ROW2");
writer.close();
}catch(Exception e){

}

如何解决这个问题?

最佳答案

我尝试了以下代码,它似乎产生了您想要的结果。

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

public class TestNewLines {

public static void main(String[] args) {
TestNewLines testFiles = new TestNewLines();
testFiles.addToFavToFile("");
}

private void addToFavToFile(String site){
BufferedWriter writer = null;
try{
writer = new BufferedWriter(new FileWriter("test.txt",true));
insertEmptyLine(writer);
writer.write("ROW1: " + System.currentTimeMillis());
insertEmptyLine(writer);
writer.write("ROW2: " + System.currentTimeMillis());
insertSeperator(writer);
writer.close();
} catch(Exception e){

}
}

private void insertEmptyLine(BufferedWriter writer) throws IOException {
writer.newLine();
writer.newLine();
}

private void insertSeperator(BufferedWriter writer) throws IOException {
writer.newLine();
writer.write("********************");
}
}

为了测试它,我添加了“这是第一行”这一行。在我的测试文件的开头。运行几次后,输出如下所示:

This is the first line.

ROW1: 1335189657127

ROW2: 1335189657127


ROW1: 1335189658390

ROW2: 1335189658390


ROW1: 1335189665738

ROW2: 1335189665738


ROW1: 1335189679638

ROW2: 1335189679638


正如您从时间戳中看到的,我每次都会在文件末尾 append 新行。

关于java - 行尾,FileWriter\n,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10280865/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com