java 파일에서 Pattern 추출 하기 도와 주세요
파일 에 내용이
REPORT_TIME=2014-05-28T09:06:00Z
REPORT_CAUSE=Analytics
X-Device-Locale=ko-KR
X-Device-Country=KR
...
이런 식으로 있을 때 특정 data 를 아래와 같이 추출 하기 위한 소스 입니다.
출력 결과 :
"REPORT_TIME"="2014-05-28T09:06:00Z" "X-Device-Country"="KR" ....
그런데 실행을 하면
"REPORT_TIME"="2014-05-28T09:06:00Z" "REPORT_TIME"="2014-05-28T09:06:00Z" "null"="null"
이런 식으로 나옵니다.
정규식과 자바를 둘다 초보라 잘 모르겠습니다. 도와주세요 ..
소스 내용 :
import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Regx_tes { //클래스
     public void webOverview(String overviewFile, String tmpFile) {
             try {
                BufferedReader in = new BufferedReader(new FileReader(overviewFile)); //overview Reading
                BufferedWriter out = new BufferedWriter(new FileWriter(tmpFile));  //replace overview file make
                String oData = "";
                StringBuffer str = new StringBuffer();
                while ((oData = in.readLine()) != null) {
                    // Matcher m1  = Pattern.compile("\\d{4}-\\d{2}-\\w+:\\w+:\\w+").matcher(mData);
                     Matcher m1  = Pattern.compile("(REPORT_TIME)=(\\d{4}-\\d{2}-\\w+:\\w+:\\w+)|(X-Device-Country)=(\\w+.*)").matcher(oData);
                     //Matcher m2  = Pattern.compile("(PRODUCT_NUM)=(\\w+)").matcher(oData);
                     while(m1.find()) {
                     str.append("\"");
                     str.append(m1.group(1));
                     str.append("\"");
                     str.append("=");
                     str.append("\"");
                     str.append(m1.group(2));
                     str.append("\" ");
                     out.write(str.toString());
                     out.flush();
                         }
          }
                        in.close();
                     } catch (IOException e) {
                      System.out.println("다음과 같은 에러가 발생하였습니다.");
                      System.err.println(e);
                     } //catch    
    } 
 public static void main(String[] args) {
  Scanner path_fileIinput = new Scanner(System.in); // script parameter -- input_path messages file name index file name
  String paramInPath = path_fileIinput.next(); // input_path
  String overviewFile = paramInPath+"/overview.txt";
  String tmpFile = paramInPath+"/tmp";
  Regx_tes web_os_test = new Regx_tes();
  try {
   web_os_test.webOverview(overviewFile,tmpFile); // overview File to temp file change
   System.out.println("done!");
  } catch (Exception e) {
   System.out.println("다음과 같은 에러가 발생하였습니다.");
   System.err.println(e);
  }
 }
}//class


내용상으로는 굳이 Pattern을 이용한 정규식
내용상으로는 굳이 Pattern을 이용한 정규식 매핑이 필요없어보이는데요...
단순히 파일 내용에
NAME=VALUE
형태로 저장되어있다면 라인단위로 읽어서
NAME, VALUE값을 추출하시면 될듯합니다.
또는
NAME=VALUE형태는 Properties형태이므로
Properties클래스를 이용하셔도 될듯합니다.
ex)
Properties prop = new Properties();
prop.load(inputstream);
댓글 달기