示例属性文件:
Label1=DataSet1
Label1.Col1=val1
Label1.Col2=val2
Label1.Col3=val3
Label1.Col4=val4
Label2=DataSet2
Label2.Col1=val1
Label2.Col2=val2
Label2.Col3=val3
Label2.Col4=val4
当我想阅读DataSet 1& 2个数据。我应该得到所有相应的密钥和&值。我怎样才能在Java中执行此代码?你能帮我吗?
数据集1:
Col1=val1
Col2=val2...
答案 0 :(得分:1)
试试这个:
<强> ReadGroupLevel.txt:强>
Label1=DataSet1
Label1.Col1=val1
Label1.Col2=val2
Label1.Col3=val3
Label1.Col4=val4
Label2=DataSet2
Label2.Col1=val1
Label2.Col2=val2
Label2.Col3=val3
Label2.Col4=val4
Label3=DataSet3
Label3.Col1=val1
Label3.Col4=val4
Label4=DataSet4
Label4.Col1=val1
Label4.Col2=val2
Label4.Col3=val3
Label4.Col4=val4
<强>代码:强>
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class readGroupLevel {
static Map<Integer,String> dataset = new HashMap<Integer, String>();
public static void main(String[] args) throws IOException {
// 1 - Read the file and sore it in "dataset"
readFile();
// 2 - Get content of dataset
System.out.println("Dataset 1:");
System.out.println(dataset.get(1));
System.out.println("Dataset 2:");
System.out.println(dataset.get(2));
System.out.println("Dataset 3:");
System.out.println(dataset.get(3));
System.out.println("Dataset 4:");
System.out.println(dataset.get(4));
System.out.println("Dataset 5:");
System.out.println(dataset.get(5));
}
/**
* Reads the file and store it in dataset
* @throws IOException
*/
private static void readFile() throws IOException{
// Read the file
FileReader in = new FileReader("src/ReadGroupLevel.txt");
BufferedReader br = new BufferedReader(in);
// Current line
String line;
// Number of dataset find
int numberDataset = -1;
// Content of current dataset
String contentDataset="";
while ((line = br.readLine()) != null) {
// Find line "Label1=DataSet1"
if(line.contains("DataSet")){
if(numberDataset!=-1){
// Fill data
dataset.put(numberDataset, contentDataset);
contentDataset = "";
numberDataset=-1;
}
// Split line "Label1=DataSet1" by "=" and get number
String[] split = line.split("=");
String nameDataset=split[1];
try{
numberDataset = Integer.parseInt(nameDataset.replace("DataSet", ""));
}catch(Exception e){
numberDataset = -1;
}
}else if(numberDataset!=-1){
// Get content
contentDataset = contentDataset+line+"\n";
}
}
// Last dataset content
if(numberDataset!=-1){
dataset.put(numberDataset, contentDataset);
}
in.close();
}
}
<强>输出:强>
Dataset 1:
Label1.Col1=val1
Label1.Col2=val2
Label1.Col3=val3
Label1.Col4=val4
Dataset 2:
Label2.Col1=val1
Label2.Col2=val2
Label2.Col3=val3
Label2.Col4=val4
Dataset 3:
Label3.Col1=val1
Label3.Col4=val4
Dataset 4:
Label4.Col1=val1
Label4.Col2=val2
Label4.Col3=val3
Label4.Col4=val4
Dataset 5:
null