我不确定如何为用户提供从现有文本文件添加/删除名称的选项。当前的代码工作正常并从文本文件中读取名称。有人可以帮我解决这个问题吗?
import java.io.File;
import java.util.Scanner;
public class AddOrDeleteNames {
public static void main(String[] args) throws Exception {
String[] names = new String[100];
Scanner scan = new Scanner(new File("names.txt"));
int index = 0;
while (scan.hasNext()){
names[index]=(scan.nextLine());
index++;
}
for(int i = 0; i < index; i++){
System.out.println(names[i]);
}
scan.close();
}
}
最佳答案
这是可能的,几乎一切都是可能的,但是你会发现使用数组很难做到。
我会使用 ArrayList
这很相似,但比普通的数组要好得多。
一个String
ArrayList
定义如下:
ArrayList<String> names = new ArrayList<String>();
您可以使用 add
添加ArrayList
的功能:
while (scan.hasNext())
names.add(scan.nextLine());
然后,要从文本文件中删除名称,只需将其从 names
中删除即可。使用 remove
的 ArrayList函数,将修改后的ArrayList写入文件:
names.remove("Some Name Here");
PrintWriter writer = new PrintWriter("names.txt", "UTF-8");
for (int i = 0; i < names.size(); i++)
writer.println(names.get(i));
writer.close();
同样,要向文件添加新名称,只需将新名称添加到 ArrayList
在将其写入文件之前,使用 add
功能
关于java - 如何从文本文件中添加/删除行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27378085/