我有文本文件如下我想將它存儲在ArrayList中,但問題是它沒有相同的鍵值對,即最後2 [參數]具有param4 = value4,param5 = value5。如何將文本文件內容存儲在arrayList ..?
如何將其存儲在arrayList或map ..?
的test.txt
[Param]
param1=value1
param2=value2
param3=value3
[Param]
param1=value1
param2=value2
param3=value3
[Param]
param1=value1
param2=value2
param3=value3
[Param]
param1=value1
param2=value2
param3=value3
[Param]
param1=value1
param2=value2
param3=value3
param4=value4
[Param]
param1=value1
param2=value2
param3=value3
param4=value4
param5=value5
Java代碼:
public class Task {
static String Filepath = "C:\\Users\\Administrator\\Desktop\\TASK\\test.txt";
static ArrayList<String> list1;
static ArrayList<String> list2;
static ArrayList<String> list3;
static HashMap<Integer, ArrayList<String>> map;
public static void main(String[] args) {
// TODO code application logic here
try {
FileInputStream fstream = new FileInputStream(Filepath);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine, user;
int lineNumber = 0;
list1 = new ArrayList<>();
list2 = new ArrayList<>();
list3 = new ArrayList<>();
map = new HashMap<>();
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
process(strLine);
lineNumber++;
}
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
map.put(1, list1);
map.put(2, list2);
map.put(3, list3);
for (int i = 0; i < list1.size(); i++) {
System.out.println("[Param]");
System.out.println("param1=" + list1.get(i));
System.out.println("param2=" + list2.get(i));
System.out.println("param3=" + list3.get(i));
}
}
public static void process(String str) {
if (str.contains("param1=")) {
String[] arr = str.split("param1=");
////System.out.println(arr[1].trim());
list1.add(arr[1].trim());
} else if (str.contains("param2=")) {
String[] arr = str.split("param2=");
//System.out.println(arr[1].trim());
list2.add(arr[1].trim());
} else if (str.contains("param3=")) {
String[] arr = str.split("param3=");
//System.out.println(arr[1].trim());
list3.add(arr[1].trim());
}
}
}
請嘗試[this](http://stackoverflow.com/a/9301067/1728206) – janani
我讀過你提供的鏈接,但它的屬性文件和唯一的鍵值對.... –
Y我們的鍵不是唯一的手段你不能存儲在哈希映射 – janani