[英]Reading External Text File and Storing into an array
如何讀取外部文本文件,可能使用掃描儀並將每行中的2個值存儲到數組中。
我想存儲節點id,它是每行的第一個值,父節點號是每行的最后一個值。
文本文件包含您在下面看到的內容
1 2,7,|0|BLACK|NULL
10 3,4,12,|3|BLACK|3
11 4,12,|4|BLACK|4
12 8,10,11,|3|BLACK|8
2 1,3,6,8,|1|BLACK|1
3 2,4,5,6,8,10,|2|BLACK|2
4 3,5,9,10,11,|3|BLACK|3
5 3,4,8,|3|BLACK|3
6 2,3,|2|BLACK|2
7 1,8,|1|BLACK|1
8 2,3,5,7,9,12,|2|BLACK|2
9 4,8,|3|BLACK|8
正則表達式方法(已將數組位作為讀者的練習):
BufferedReader br = new BufferedReader(new FileReader("hadoop_data.txt"));
String currentLine;
while ((currentLine = br.readLine()) != null) {
Matcher matcher = Pattern.compile("(\\d+).*\\|(\\w+)").matcher(currentLine);
if (matcher.matches()) {
System.out.println(matcher.group(1) + "\t" + matcher.group(2));
// add to array
}
}
Shonna,你可以使用HashMap,Scanner和一些簡單的字符串解析來實現你想要的。 這是我的全班:
import java.io.*;
import java.util.*;
public class nodes {
private static HashMap<Integer, String> map = new HashMap<Integer, String>();
public static void main(String[] args) {
File file = new File("nodes.txt");
Scanner scnr = null;
try {
scnr = new Scanner(file);
} catch (FileNotFoundException e) {
}
while(scnr.hasNext()) {
String line = scnr.nextLine();
String[] getId = line.split("\\s+");
int id = Integer.parseInt(getId[0]);
int count = 0;
int copy = 0;
for(int i = 0; i < line.length(); i++) {
if(line.charAt(i) == '|')
count++;
if(count == 3) {
copy = i;
break;
}
}
String parent = line.substring(copy + 1);
map.put(id, parent);
System.out.println(map);
}
}
}
它的作用是讀取文件的每一行,首先提取節點ID。 然后它循環遍歷行中的每個字符,直到它計算三個|
那時,我們知道該行的其余部分將是節點的父節點。 完成此操作后,它將id與HashMap中的父對配對。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.