首页 > 解决方案 > 如何将arraylist逐行附加到txt文件中?

问题描述

我正在尝试将数组列表的一项添加到 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

我一直在尝试不同的事情,比如将 append not write 放在 BufferedWriter 方法中,但它仍然给出相同的结果。我怎样才能做得更好?

标签: javafilearraylist

解决方案


  1. 您应该使用try-with-resources来自动关闭资源。
  2. 将文件中的行加上相应的用户名存储到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);
            }
        }
    }
}

推荐阅读