java—如何将arraylist逐行追加到txt文件中?

myzjeezk  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(439)

我正在尝试将arraylist的一项添加到txt文件中,但我需要逐行添加。txt文件包含名称,我正在尝试添加它们的用户名,所以我需要逐行添加每个用户。这是原始的txt文件:

Smith, Will
Lothbrok, Ragnar
Skywalker, Anakin
Ronaldo, Cristiano
Messi, Lionel

这是我使用的方法:

public static void addUsers(int maxLines,  List<Users> users) throws IOException {
    File f = new File("Users.txt");
    FileOutputStream fos = new FileOutputStream(f, true);

    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));

    //maxLines is just a count of the lines from the text file so i can put the limit of this loop.
    for (int i = 0; i < maxLines; i++) {
        bw.write(" > " + users.get(i).getUsername() );
        bw.newLine();
    }

    bw.close();
}

我得到的结果是:

Smith, Will
Lothbrok, Ragnar
Skywalker, Anakin
Ronaldo, Cristiano
Messi, Lionel
 > Will.Smith3
 > Ragnar.Lothbrok74
 > Anakin.Skywalker30
 > Cristiano.Ronaldo32
 > Lionel.Messi2

但我需要这样:

Smith, Will > Will.Smith3
Lothbrok, Ragnar > Ragnar.Lothbrok74
Skywalker, Anakin > Anakin.Skywalker30
Ronaldo, Cristiano > Cristiano.Ronaldo32
Messi, Lionel > Lionel.Messi2

我一直在尝试不同的方法,比如在bufferedwriter方法中添加append not write,但仍然得到相同的结果。我怎样才能做得更好?

gopyfrb3

gopyfrb31#

应该使用try with resources自动关闭资源。
将文件中的行以及相应的用户名存储到 List<String> 读取文件时。读取完成后,将此列表的内容写入文件。
演示:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

class User {
    private String username;

    public User(String username) {
        this.username = username;
    }

    public String getUsername() {
        return username;
    }
}

public class Main {
    public static void main(String[] args) {
        // Test
        List<User> users = List.of(new User("Will.Smith3"), new User("Ragnar.Lothbrok74"),
                new User("Anakin.Skywalker30"), new User("Cristiano.Ronaldo32"), new User("Lionel.Messi2"));
        try {
            addUsers(5, users);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    static void addUsers(int maxLines, List<User> users) throws IOException {
        // List to store lines from the file plus corresponding username
        List<String> list = new ArrayList<>();

        try (BufferedReader reader = new BufferedReader(new FileReader(new File("Users.txt")))) {
            String currentLine;
            int line = 0;
            while ((currentLine = reader.readLine()) != null && line < users.size()) {
                list.add(line, currentLine + " > " + users.get(line).getUsername() + System.lineSeparator());
                line++;
            }
        }

        // Write the content of the list into the file
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(new File("Users.txt")))) {
            for (String s : list) {
                writer.write(s);
            }
        }
    }
}

相关问题