gpt4 book ai didi

java - 我如何让我的代码将数据连接在一起而不是用每个新流覆盖 .txt 文件

转载 作者:行者123 更新时间:2023-11-29 05:18:57 24 4
gpt4 key购买 nike

我很难让我的程序将 URL 中的所有 XML 数据添加到 .txt 文件中,而不总是覆盖上述文件中已有的数据。我正在尝试使用该程序将 channel 上传的所有视频的 XML 数据保存到一个 .txt 文件中,稍后将引用该文件。

filename = new File("xmlData.txt");
filename.createNewFile();

while (flag1 == 0)
{
URL url = new URL("https://gdata.youtube.com/feeds/api/users/"+Name+"/uploads? max-query=50&start-index="+index);

try (BufferedReader br = new BufferedReader(
new InputStreamReader(url.openStream())))
{
while ((inputLine = br.readLine()) != null)
{
try (BufferedWriter bw = new BufferedWriter(new FileWriter(filename)))
{
bw.write(inputLine);
bw.newLine();
}
}
}

if (count1 < 25)
{
index = index+50;
count1++;
}
else
{
flag1 = 1;
}
}

System.out.println("Done writing to xmlData.txt");

最佳答案

FileWriter构造函数允许传递第二个 boolean 参数,append

Javadoc 声明:

Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.

Parameters:
file a File object to write to
append if true, then bytes will be written to the end of the file rather than the beginning

因此,像这样创建一个 FileWriter:

new FileWriter(filename, true);

此外,我会在 while 循环的外部 打开文件。这将使您的文件打开一次并在您从 XML 文件 (URL) 读取时追加到文件中。

关于java - 我如何让我的代码将数据连接在一起而不是用每个新流覆盖 .txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25531263/

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