FileWriter方法仅写入最后一行 [英] FileWriter method is only writing last line

查看:150
本文介绍了FileWriter方法仅写入最后一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个fileWrite()方法,该方法接受两个字符串值作为参数(特定的数组值).我将此方法包含在for循环中,以便它可以遍历数组并获取字符串值以写入文件

I have a fileWrite() method that accepts two string values as parameters(specific array values). I include this method in a for loop so it can loop through the array and get the string values to write to the file

public void writeFile(String ip, String vals) {

    try {

         bw = new BufferedWriter(new FileWriter("Finished.txt"));

        bw.write(ip + ": " + vals );
        bw.newLine();


        bw.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

在代码中包含该方法的位置如下所示:

and where i include the method in my code looks as follows:

for (int i = 0 ; i  < address.length ; i++) {
writeFile(address[i][0], address[i][1]);
        }

似乎只将数组中的最后一个值写入文本文件.

it seems only to write the last values in the array to the text file.

推荐答案

您每次调用该文件都会覆盖该文件

You are overwriting the file on every call to

new BufferedWriter(new FileWriter("Finished.txt"));

最好打开一次文件,写入所有数据,然后关闭它.

You are better off opening the file once, writing all your data, and then closing it.

这篇关于FileWriter方法仅写入最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆