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

Java 如何让代码将数据连接在一起,而不是用每个新流覆盖.txt文件,java,bufferedreader,filewriter,bufferedwriter,Java,Bufferedreader,Filewriter,Bufferedwriter,我很难让我的程序将URL中的所有XML数据添加到一个.txt文件中,而不总是写入前面提到的文件中已有的数据。我正在尝试使用该程序将频道上传的所有视频的XML数据获取到一个.txt文件中,稍后将引用该文件 filename = new File("xmlData.txt"); filename.createNewFile(); while (flag1 == 0) { URL url = new URL("https://gdata.youtube.com/feeds/api/users

我很难让我的程序将URL中的所有XML数据添加到一个.txt文件中,而不总是写入前面提到的文件中已有的数据。我正在尝试使用该程序将频道上传的所有视频的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");
filename=新文件(“xmlData.txt”);
filename.createNewFile();
while(flag1==0)
{
URL=新URL(“https://gdata.youtube.com/feeds/api/users/“+Name+”/uploads?max query=50&start index=“+index”);
try(BufferedReader br=新的BufferedReader(
新的InputStreamReader(url.openStream()))
{                
而((inputLine=br.readLine())!=null)
{        
try(BufferedWriter bw=new BufferedWriter(new FileWriter(filename)))
{
写入(输入线);
换行符();
}
}
}
如果(计数1<25)
{
指数=指数+50;
count1++;
}
其他的
{
flag1=1;
}
}
System.out.println(“写入xmlData.txt完成”);

文件编写器的第二个参数是
布尔追加
。看到和

构造函数不允许传递第二个布尔参数,
append

Javadoc声明:

在给定文件对象的情况下构造FileWriter对象。如果第二个 参数为true,则字节将写入文件末尾 而不是开始

参数:
文件要写入的文件对象
追加如果
为true
,则字节将写入文件的末尾而不是开头

因此,创建一个文件编写器,如下所示:

new FileWriter(filename, true);

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

+1对于“在循环外打开编写器”,我在想,为什么OP会这样做?太棒了!我看到OP正在使用新的,所以我想这就是为什么?tbh我甚至没有想到这一点。它开始时没有循环,因为我原本以为gdata会给我所有视频的所有xml数据。但是,它只返回50个结果,然后需要为下一个50个结果建立索引,以此类推。所以我只是用旗子和计数器在里面打了个圈。我现在就要把它全部改了。@BuhakeSindi我喜欢这个新功能,但我没听说过。不过,我已经两年多没有编写Java了。@CamthraX您应该确保接受这里的建议,我不知道为什么要从循环中打开多个编写器
new FileWriter(filename, true);