java - 如何将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 方法中,但它仍然给出相同的结果。我怎样才能做得更好?
解决方案
- 您应该使用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);
}
}
}
}
推荐阅读
- python - DataFrame.to_csv 抛出错误“[Errno 2] 没有这样的文件或目录”
- ruby-on-rails - 乐观锁定是否适用于使用 update_all 中的 updated_at 属性的以下代码?
- dart - Flutter - 删除飞镖中的转义序列
- java - 添加对象 onStartPage itextPdf 除了最后一页
- math - 语料库分数计算
- c# - Dynatrace OneAgent 如何更改 dotnet 应用程序 HTTP 标头
- python-3.x - 异质化numpy数组,使得没有两个相邻的单元格相等
- appium - Appium 中的此元素无法进行交互
- runtime-error - RAD Studio 10.2 (C++):~TControl() 析构函数仅适用于每第二次迭代
- javascript - Google 表格如何覆盖浏览器快捷方式?