如果文本文件是空間對齊的,您可以(也可能應該)根據字符數提取字段。因此,您將每行中的第一個n
字符作爲名字,下一個m
字符作爲城市,等等。
這是一個使用上述方法提取的代碼,通過自動計算字段的字段長度,假設我們知道標題。
String data = "data from the file";
// This is just to ensure we have enough space in the array
int numNewLines = data.length()-data.replace("\n","").length();
String[][] result = new String[numNewLines][3];
String[] lines = data.split("\n");
int avgSalary = 0;
int secondFieldStart = lines[0].indexOf("City");
int thirdFieldStart = lines[0].indexOf("Zip");
for(int i=1; i<lines.length; i++){
String line = lines[i].trim();
if(line.equals("Avg Salary")){
avgSalary = Integer.parseInt(lines[i+1].substring(0,secondFieldStart).trim());
break;
}
result[i-1][0] = line.substring(0,secondFieldStart).trim(); // First Name
result[i-1][1] = line.substring(secondFieldStart,thirdFieldStart).trim(); // City
result[i-1][2] = line.substring(thirdFieldStart).trim(); // Zip
}
使用正則表達式將是可能的,但它會更復雜。而正則表達式將無法區分人的姓名和城市的名字呢:
考慮這種情況下:
John Long-name Joe New York 21003
你怎麼知道的名字是John Long-name Joe
而不是John Long-name Joe New
,如果你不知道做第一個字段的長度不超過20個字符? (注意John Long-name Joe
是長度爲19個字符,在New York
離開它和New
之間有一個空格)
當然,如果你的領域是由其他字符分隔(如製表符\t
),您可以拆分根據每條線路。而且很容易修改上面的代碼,以適應=)
由於我上面提出的解決方案是簡單的,我猜你可能想嘗試它,而不是=)
和你有什麼解析? –
http://stackoverflow.com/questions/20621252/how-to-split-a-file-into-multiple-arrays-display-them-and-perform-calculations/20621864#20621864這將有助於 – Ashish
我試圖獲得姓名,城市,郵編,然後是工資,百分比細節 – user3084618