2016-03-23 104 views
-1

我的輸入文件(My.txt文件)是以下格式(製表符分隔值):處理分隔符分隔值

"0" "0" "231" "1193" 

"0" "0" "74" "457" 

"0" "0" "530" "387" 

"0" "0" "1221" "641" 

"0" "0" "328" "428" 

"0" "0" "228" "979" 

我寫了下面的代碼讀取此輸入。但是,分隔符是一個問題。有沒有辦法在Java中,我可以忽略分隔符,只有價值?

try { 
    FileReader reader = new FileReader("/home/brina/Desktop/my.txt"); 
    BufferedReader brReader = new BufferedReader(reader); 

    String line; 
    while ((line = brReader.readLine()) != null) { 
     String[] data = line.split("\t"); 
     if ((Integer.parseInt(data[2]) > 200) && (Integer.parseInt(data[3]) > 1000)) { 
      System.out.println("\tYes"); 
     } else { 
      System.out.println("\tNo"); 
     } 

    } 
    brReader.close(); 
} catch (final FileNotFoundException e) { 
    e.printStackTrace(); 
} catch (final IOException e) { 
    e.printStackTrace(); 
} 
+0

什麼是分隔符? –

+0

你的問題是什麼? 'split'不包含分隔符。可能,這不應該是問題。 – rpy

回答

1

我想你可以使用正則表達式:

Pattern p = Pattern.compile("^\"\\d+\"\\t\"\\d+\"\\t\"(\\d+)\"\\t\"(\\d+)\"$"); 
while ((line = brReader.readLine()) != null) { 
    Matcher m = p.matcher(line); 
    if (Integer.valueOf(m.group(1)) > 200 && Integer.valueOf(m.group(2)) > 1000) 
    { 
    System.out.println("\tYes"); 
    } 
    else 
    { 
    System.out.println("\tYes"); 
    } 
} 
+0

我也加入了一個開始'^'並停止'$'到那個正則表達式 – flakes

+0

的確,我編輯了代碼,謝謝。 – RemyG

0

你將不得不搶串出了報價,將其轉換爲一個int,然後我會建議將它添加到一個int列表。這樣的事情:

String line; 
while ((line = brReader.readLine()) != null) 
{ 
    String[] data = line.split("\t"); 
    List<int> listInt = new List<int>(); 
    for (int i = 0; i < data.Length; i++) 
    { 
    listInt = new List<int>(); 
    String intOnly = data[i].substring(1, data[i].Length - 1); //adjust these values if needed 
    int add = Integer.parseInt(intOnly); 
    listInt.Add(add); 
    } 
    if (listInt[2] > 200 && listInt[3] > 1000) 
    { 
    System.out.println("\tYes"); 
    else 
    { 
     System.out.println("\tNo"); 
    } 
    } 
} 
2

您可以使用匹配器來只提取整數值,並且它不會影響你在該行上有什麼。水木清華像

List<Integer> numbers = new ArrayList<>(); 
Matcher matcher = Pattern.compile("\\d+").matcher(line); 
while (matcher.find()) { 
    numbers.add(matcher.group()); 
} 
0

隨着Commons CSV閱讀製表符分隔的文件很簡單:

final Charset utf = Charset.forName("UTF-8"); 
final Path path = Paths.get("/home/brina/Desktop/my.txt"); 

try (CSVParser p = new CSVParser(Files.newBufferedReader(path, utf), CSVFormat.TDF)) { 
    for (CSVRecord r : p) { 
     int v1 = Integer.parseInt(r.get(2)); 
     int v2 = Integer.parseInt(r.get(3)); 
     System.out.println(v1 > 200 && v2 > 1000 ? "\tYes" : "\tNo"); 
    } 
} catch (IOException e) { 
    // ... 
}