我正在尝试从文本文件中读取以下内容
12
650 64 1
16 1024 2
如何将其放入列表或为其提供变量?
试过这个
class Test{
Scanner lese = new Scanner(new File("regneklynge.txt"));`
ArrayList<String> list = new ArrayList<String>();`
while (lese.hasNext()){`
list.add(lese.next());`
}
}
答案 0 :(得分:0)
检查this article我们是否从文件中读取。
然后,您可以使用Java's Scanner class阅读单个项目并将其放入列表中。
例如:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
public class ReadFromFile {
public static void main(String[] args) {
File file = new File("file-name.txt");
try {
Scanner scanner = new Scanner(file);
List<Integer> myIntList = new ArrayList<>();
while (scanner.hasNext()) {
int i = scanner.nextInt();
myIntList.add(i);
}
scanner.close();
// now you have an ArrayList with the numbers in it that you can use
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}