我正在尝试编写一种方法,用新的字符串更新 .txt 文件......我所做的就是 1)从之前创建的 txt 文件中读取所有字符串 2)将它们放入数组列表中 3) 将一个新字符串写入arraylist 4) 然后将该 arraylist 的 toString() 对象写入新文件
即使我编辑多行文件,它也只将最新的字符串写入文件,而不写入其他字符串
这是我所拥有的:
public static void updateNames(String newName) throws FileNotFoundException {
name = new File("names.txt");
infile = new Scanner(name);
ArrayList<String> nameslist = new ArrayList<>();
while(infile.hasNext()) {
nameslist.add(infile.nextLine());
}
infile.close();
nameslist.add(newName);
names = new PrintWriter("names.txt");
for(int i=0;i<nameslist.size();i++) {
names.println(nameslist.get(i).toString());
}
names.close();
System.out.println("else");
}
为了尽可能清楚地说明,{name、names 和 infile} 在类的开头都声明为 static void
提前感谢您的帮助
最佳答案
使用infile.hasNextLine()
代替infile.hasNext()
改变
while(infile.hasNext())
至
while(infile.hasNextLine())
和小修正
改变
names.println(nameslist.get(i).toString());
至
names.println(nameslist.get(i)); //nameslist holds String objects no need to convert to String again.
如果问题没有解决,请添加 countline 变量并确保从文件中读取了多少行。
int countline;
while(infile.hasNext()) {
nameslist.add(infile.nextLine());
countline++;
}
System.out.println("Number of line: "+ countline);
关于java - 使用字符串更新 .txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20237356/