2015-02-05 4 views
0

파일의 모든 행에 대해 메서드를 호출해야하는 Java 응용 프로그램을 작성하고 있습니다. 그런 다음 사용자 지정 대화 상자를 엽니 다. 나는 파일 읽기이 코드를 사용하고 있습니다 :Java 파일의 각 행에 대한 메서드 호출

 List<String> lines = new ArrayList<String>(); 
     String line = null; 
     try { 
      BufferedReader reader = new BufferedReader(new FileReader("test.ospt")); 
      while((line = reader.readLine()) != null){ 
       lines.add(line) ; 
      } 
     } catch (Exception e1) { 
      e1.printStackTrace(); 
     } 

     for(String line1 : lines) 
     { 
      execute(line1); 
     } 

을 그리고 이것은 실행() 방법 :

public static void execute(String script) { 
    if (script.contains("tell $DESKTOP -dialog")) { 
     String s = txt.getText(); 
     Matcher m = Pattern.compile("\\[([^)]+)\\]").matcher(s); 
     String stuff = null; 
     while(m.find()) { 
      stuff = m.group(1); 
     } 
     String[] dialogParts = stuff.split(","); 
     String part1 = dialogParts[0].trim().replaceAll("\"", ""); 
     String part2 = dialogParts[1].trim().replaceAll("\"", ""); 
     String part3 = dialogParts[2].replaceAll("\\s+", ""); 
     int part3int = Integer.parseInt(part3); 

     if (part3int == 0) { 
      JOptionPane.showMessageDialog(Mainframe.instance, part2, part1, JOptionPane.INFORMATION_MESSAGE); 
     } 

     if (part3int == 1) { 
      JOptionPane.showMessageDialog(Mainframe.instance, part2, part1, JOptionPane.ERROR_MESSAGE); 
     } 

     if (part3int == 2) { 
      JOptionPane.showMessageDialog(Mainframe.instance, part2, part1, JOptionPane.WARNING_MESSAGE); 
     } 

     if (part3int == 3) { 
      JOptionPane.showMessageDialog(Mainframe.instance, part2, part1, JOptionPane.QUESTION_MESSAGE); 
     } 
    } 
} 

그러나 파일의 각 줄에() 실행 호출하는 루프이 사용 후 :

'line1'을 전체 파일로 취급하므로 실행시 전체 파일을 읽을 수 없으므로 오류가 발생합니다. 전체 파일을 읽는 대신에 각 행을 execute() 메소드에 넣을 수 있습니까?

+0

여기서'execute' 내에'script'를 사용하고 있습니까? –

+0

LF vs CR 문제처럼 보입니다 ... 어떤 운영 체제를 사용하고 있으며 텍스트 파일을 만들기 위해 어떤 편집기를 사용 했습니까? – jwatkins

+0

죄송합니다, 코드가 오류가 있습니다. txt.getText()가 'script'여야했습니다. –

답변

0

직접 제목의 질문에 대답하려면 ...

당신이 다음과의 반복을 대체 할 수있는 자바 (8)를 사용하는 경우 더 나은

lines.forEach(MyClass::execute); 

또는 당신은에서 직접 호출 할 수 있습니다 읽은대로 행 :

Files.lines(Path.get(path)).forEachOrdered(MyClass::execute);