[英]How to read a list of ArrayLists from file?
我正在嘗試讀取一個包含圖的鄰接表的文件。 該文件如下所示:
1 2 3 5
2 4
3 1 5
4
5 2 4
每行是一個鏈表,其長度不同於其他行。 到目前為止,我已經嘗試過了:
private static List<ArrayList<String>> adj;
ArrayList<String> rows = new ArrayList<String>();
int i = 0;
try {
Scanner input = new Scanner(new BufferedReader(new FileReader(fileName)));
//BufferedReader input = new BufferedReader(new FileReader(fileName));
String line;
while (input.hasNextLine()){
i++;
String[] cols = input.nextLine().trim().split(" ");
for (String c : cols){
rows.add(c);
}
adj.add(rows);
}
//print the matrix
for (List<String> list : adj) {
for (String str : list) {
System.out.print(str + " ");
}
System.out.println();
}
}
catch (IOException e){
System.out.println("Error reading input file!");
}
但它不起作用,因為當我嘗試打印整個矩陣時會顯示錯誤(NullPointerException)。 如何正確讀取此文件?
編輯后,我復制了您的代碼,對列表進行了初始化,添加了try / catch並添加了打印代碼,這工作正常:
List<ArrayList<String>> adj = new ArrayList<>();
int i = 0;
Scanner input = null;
try {
input = new Scanner(new BufferedReader(new FileReader(fileName)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String line;
while (input.hasNextLine()) {
ArrayList<String> rows = new ArrayList<String>();
i++;
String[] cols = input.nextLine().trim().split(" ");
for (String c : cols) {
rows.add(c);
}
adj.add(rows);
}
for (ArrayList<String> list : adj) {
for (String s : list) {
System.out.print(s + " ");
}
System.out.println();
}
為此,您實際上應該使用來自“新” Java NIO(在Java 7中引入)的方法以及流(在Java 8中引入)。
public void readLinesExample(String fileName) throws IOException {
List<List<String>> adj = Files.readAllLines(Paths.get(fileName)).stream()
.map(row -> row.split(" "))
.map(Arrays::asList)
.collect(toList());
System.out.println(adj.stream().flatMap(Collection::stream).collect(joining(" ")));
}
這幾行完成了所有工作,並包裝在main()
方法中。
這很簡單:
IOException
因此,如果您確實想通過打印到標准輸出來處理異常,則可能需要將其包裝在示例中。 map(Arrays::asList)
從每個數組創建一個List
。 打印部分同樣簡單。 它在列表列表上進行流式處理,並使用平面映射將子列表“平化”為一個流。 然后將元素連接到一個字符串,並用" "
分隔,並進行打印。
與原始代碼相比,這不容易出錯,您幾乎不會做錯任何事情。 當然,它在一些次要方面有所不同,例如toList()
不能保證您得到ArrayList
,但這並不重要。
在使用Java 8的另一種方法中,您可以簡化代碼並編寫類似的內容以讀取包含圖形或任何類似數據的鄰接表的文件。
public static void printGraph() throws Exception {
List<String> numberList = Files.readAllLines(Paths.get("graph.txt")); // reads all lines in one shot into a List<String>
List<List<Integer>> listOfIntegerList = new ArrayList<List<Integer>>();
for (String s : numberList) { // for each line containing numbers, stores them into a List<Integer>
listOfIntegerList.add(Arrays.stream(s.split("\\s+")).map(Integer::parseInt).collect(Collectors.toList()));
}
System.out.println(listOfIntegerList);
}
根據文件中存在的數據,這將提供以下輸出,
[[1, 2, 3, 5], [2, 4], [3, 1, 5], [4], [5, 2, 4]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.