2011-11-16 1 views
0

자바 텍스트 파싱에 익숙하지 않고 각 행의 형식을 알 때 파일을 구문 분석하는 가장 좋은 방법이 무엇인지 궁금합니다.Java에서 C 스타일로 구문 분석 하시겠습니까?

나는 각 줄의 형식은 다음 파일이 있습니다

지능, 문자열, 두 번, 문자열, 두 번, 문자열, 두 번, 두 번 문자열, 문자열, 더블

참고 어떻게 문자열 , 쉼표로 구분 된 쌍의 쌍으로 행동하고 각 쌍은 세미콜론으로 구분됩니다.

몇 가지 예 :

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"구문 분석을 수행하려는 경우 "다음"필드에 누적되는 문자가 포함 된 버퍼는 어디에 있습니까? 필드 구분 기호를 읽었는지 확인하는 곳은 어디입니까? 그리고 줄/필드 구분 기호의 끝을 읽은 후 올바른 데이터 구조로 현재 필드를 플러시하는 코드는 어디에 있습니까?

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(); 
을 사용할 수 있습니다처럼

문자로 문자가 자바에서 루프를 읽어 본다