2014-02-25 63 views
1

我一直在Java項目中工作,我需要閱讀一個看起來像這樣的文本文件如何讀取由Java中的空格分隔的字符串和數字?

1 1'誰是阿爾伯特愛因斯坦? 「司令」「物理學家」「醫生」 1 我需要單獨取值,例如ID = 1,類型= 1,問題=誰是愛因斯坦,ANSWER1 =司令等

有一些方法我可以通過空格分開它們,並將字符串作爲一個整體保持在一起?

+1

你會好起來的存儲以此爲TSV/CSV,JSON或XML。已經有解析器可以很好地處理這些格式,並且文件格式得到廣泛的支持。 –

回答

1

這很難做到,因爲標準的字符串拆分不會理解不將引號內的任何內容分開。

您可以輕鬆地編寫自己的手動分割,循環切換,每次找到報價時都會翻轉「inQuote」標誌。在找到空格並且未設置標誌時將空格拆分。

0

這應該工作:

try { 
    BufferedReader reader = new BufferedReader(new FileReader("the-file-name.txt")); 
    ArrayList<ArrayList<String>> lines = new ArrayList<ArrayList<String>>(); 
    String line = reader.readLine(); 
    while(line != null) { 
     ArrayList<String> values = new ArrayList<String>(); 
     String curr = ""; 
     boolean quote = false; 
     for(int pos = 0; pos < line.length(); pos++) { 
      char c = line.charAt(pos); 
      if(c == '\'') { 
       quote = !quote; 
      } 
      else if(c == ' ' && !quote) { 
       values.add(curr); 
       curr = ""; 
      } 
      else { 
       curr += c; 
      } 
     } 
     lines.add(values); 
     line = reader.readLine(); 
    } 
    reader.close(); 
    // Access the first value of the first line as an int 
    System.out.println("The first value * 2 is " + (Integer.parseInt(lines.get(0).get(0)) * 2)); 

    // Access the third value of the first line as a string 
    System.out.println("The third value is " + lines.get(0).get(2)); 
} catch (IOException e) { 
    System.out.println("Error reading file: "); 
    e.printStackTrace(); 
} catch (Exception e) { 
    System.out.println("Error parsing file: "); 
    e.printStackTrace(); 
} 
相關問題