在Java中,如何从文本文件中读取输入并将这些输入放入ArrayList?
所以我想在一个文本文件中读取一组包含如下字符串的输入:在Java中,如何从文本文件中读取输入并将这些输入放入ArrayList?,java,string,arraylist,Java,String,Arraylist,所以我想在一个文本文件中读取一组包含如下字符串的输入: abc456 mnjk452 aaliee23345 poitt78 我想将这些输入中的每一个放入一个数组列表,并通过我的一个方法传递该数组列表。我该怎么做呢?目前,在我的代码中,我试图看看是否可以简单地打印出arraylist中的内容。以下是我的主要观点: public static void main(String[] args) { if(args.length < 1) { Syste
abc456
mnjk452
aaliee23345
poitt78
我想将这些输入中的每一个放入一个数组列表,并通过我的一个方法传递该数组列表。我该怎么做呢?目前,在我的代码中,我试图看看是否可以简单地打印出arraylist中的内容。以下是我的主要观点:
public static void main(String[] args) {
if(args.length < 1) {
System.out.println("Give me a file!");
}
String fname = args[0];
ArrayList<String> coordinates = new ArrayList<String>();
Scanner grid = new Scanner(fname);
while(grid.hasNext()) {
coordinates.add(grid.nextLine());
}
for(String coordinate : coordinates) {
System.out.println(coordinate);
}
}
这个怎么样:
Path path = Paths.get(args[0]);
List<String> coordinates = Files.readAllLines(path);
System.out.print(coordinates); // [abc456, mnjk452, aaliee23345, poitt78]
扫描仪也可以实现同样的功能:
Path path = Paths.get(args[0]);
List<String> result = new ArrayList<>();
Scanner sc = new Scanner(path);
while (sc.hasNextLine()) {
String line = sc.nextLine();
result.add(line);
}
System.out.print(result); // [abc456, mnjk452, aaliee23345, poitt78]
在IDE或命令行中运行应用程序时,不要忘记传递参数 读取文件时,需要创建一个文件对象,并将其提供给扫描仪对象。此外,您还应该基于grid.hasNextLine控制while循环,因为您正在逐行抓取。最后,当从终端运行程序时,您应该执行以下操作 具有主文件名的类的java名称 将该文件作为参数传递给args[0]
try
{
Scanner grid = new Scanner(new File(fname));
while(grid.hasNextLine())
{
coordinates.add(grid.nextLine());
}
}catch(FileNotFoundException e)
{
System.err.println("File " + fname + " does not exist/could not be found");
e.printStackTrace();
}
你的代码现在做什么?这和预期有什么不同?我想我根本不在文本文件中阅读。当我运行程序时,它会给我一个文件!提示,我已经设置好了,你是如何读取文件的?