2011-11-16 91 views
0

我是新來的java文本解析,我想知道什麼是解析文件時,每行的格式是已知的最佳方式。用C風格解析Java?

我有了每行以下格式的文件:

詮釋;字符串,雙,字符串,雙,字符串,雙,字符串,雙,字符串,雙

說明如何使用String ,雙作爲由逗號分隔的一對,每對用分號分隔。

舉幾個例子:

1;art,0.1;computer,0.5;programming,0.6;java,0.7;unix,0.3 
2;291,0.8;database,0.6;computer,0.2;java,0.9;undegraduate,0.7 
3;coffee,0.5;colombia,0.2;java,0.1;export,0.4;import,0.5

我用下面的代碼讀取每個行:

public static void main(String args[]) { 
    try { 
     // Open the file that is the first 
     // command line parameter 
     FileInputStream fstream = new FileInputStream("textfile.txt"); 
     // Get the object of DataInputStream 
     DataInputStream in = new DataInputStream(fstream); 
     BufferedReader br = new BufferedReader(new InputStreamReader(in)); 
     String strLine; 
     // Read File Line By Line 
     while ((strLine = br.readLine()) != null) { 
      // Print the content on the console    
      System.out.println(strLine); 
     } 
     // Close the input stream 
     in.close(); 
    } catch (Exception e) {// Catch exception if any 
     System.err.println("Error: " + e.getMessage()); 
    } 
} 

感謝提前:)

回答

4

你可以使用Scanner類,初學者:

一個簡單的文本掃描器,它可以使用正則表達式分析原始類型和字符串。

0

如果你真的想做「C」風格的解析,那麼包含字符的緩衝區是爲「下一個」字段累積的呢?檢查字段分隔符是否被讀取的檢查在哪裏?一旦讀取行/字段分隔符的結尾,代碼將當前字段刷新到正確的數據結構中?

由字符的字符在Java中讀取循環看起來像

int readChar = 0; 
while ((readChar = in.read()) != -1) { 
    // do something with the new readChar. 
} 
0

您可以提供一個模式,並使用Scanner

String input = "fish1-1 fish2-2"; 
java.util.Scanner s = new java.util.Scanner(input); 
s.findInLine("(\\d+)"); 
java.util.regex.MatchResult result = s.match(); 
for (int i=1; i<=result.groupCount(); i++) 
    System.out.println(result.group(i)); 
s.close();