[英]How do I read 2 particular columns in Java from a txt file?
如何從.txt
文件中讀取第2列(第1列和第3列)。這些列由不同的定界符分隔(我想忽略寫入(基數為16的)第2列)。 另外,我如何跳過列標題。 .txt
文件如下所示:
IOU/AB-L Organization
company_id Organization
Address
D0-AB-DB (hex) Ahenhen ViewAt Technology Co.,Ltd.
D0ABDB (base 16) Ahenhen ViewAt Technology Co.,Ltd.
9A,Microprofit,6th Gaoxin South Road, High-Tech
Industrial Park, Nanshan, henzhen.
henzhen guangdong 51867
DN
42-05-F5 (hex) Integrated Technology (Malaysia) Sdn. Bhd.
4205F5 (base 16) Integrated Technology (Malaysia) Sdn. Bhd.
Phase 1, Bayan Aepas FIZ
Bayan Lepas Penang 11923
NY
我正在嘗試的代碼是:
String line;
BufferedReader reader = new BufferedReader(new FileReader(path));
while ((line = reader.readLine()) != null)
{
String[] parts = line.split(" ", 3);
if (parts.length >= 3)
{
String key = parts[0];
String value = parts[2];
System.out.println("Key value pair is "+key+" "+value);
}
}
所以基本上我想閱讀D0-AB-DB
和Ahenhen ViewAt Technology Co.,Ltd.
在第一線,然后是42-05-F5
和Integrated Technology (Malaysia) Sdn. Bhd.
Integrated Technology (Malaysia) Sdn. Bhd.
在第二行。
有人可以建議編輯嗎?
在這種情況下,我應該使用什么正則表達式?
提前致謝!
您可以在拆分方法中使用“ \\ s +”代替“”,以空格分隔字符串
我很確定您會在這里找到想要的東西: https : //docs.oracle.com/javase/8/docs/api/index.html?java/util/StringTokenizer.html
它們的關鍵是在至少2個空格 \\s{2,}
進行拆分,使用拆分限制4,並使用布爾值來知道您是否已通過標頭,或者忽略了細節行:
boolean passedHeader = false;
boolean skipDetail = false;
String line;
BufferedReader reader = new BufferedReader(new FileReader(path));
while ((line = reader.readLine()) != null) {
line = line.trim();
if (!passedHeader) { // skip header
if (line.isEmpty()) {
passedHeader = true;
}
continue;
}
if (skipDetail) { // skip detail
if (line.isEmpty()) {
skipDetail = false;
}
continue;
}
if (line.isEmpty()) { // skip empty lines
continue;
}
String[] parts = line.split("\\s{2,}", 4);
if (parts.length >= 3) {
String key = parts[0];
String value = parts[2];
System.out.println("Key: \"" + key + "\" Value: \"" + value + "\"");
} else {
System.out.println("Encountered the following line of unexpected format:");
System.out.println(line);
}
skipDetail = true;
}
注意事項 :
我重新格式化了控制台輸出,添加了雙引號以清楚地顯示所有內容。
我為行的格式意外時添加了else,這是因為任何行碰巧都是像D0-AB-DB (hex)
( D0-AB-DB
和(hex)
之間只有一個空格)
拆分限制為3,輸入行為4列或更多時,將發生以下情況。 所有額外的列都包含在第三列的文本中。 即與以下內容:
D0-AB-DB (hex) Ahenhen ViewAt Technology Co.,Ltd. Column 4 text
你會得到:
Key: "D0-AB-DB" Value: "Ahenhen ViewAt Technology Co.,Ltd. Column 4 text"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.