2014-04-02 2 views
0

그래서 txtfile에서 코드 조각을 추출하려고합니다. 조각의 시작은 "#EMPIRES"로 표시되고 끝은 '#'으로 시작하는 다른 문자열로 표시됩니다. 내 프로그램 그러나 결코 조각의 시작을 발견하고 파일의 끝에 도달 할 때까지 계속.텍스트 파일이 완전하게 읽히지 않는 이유는 무엇입니까?

문제의 원인을 파악하기 위해 먼저 발견 한 모든 줄을 인쇄 해 보았습니다. 여기 다른 문제가 발생했습니다. 내 코드는 이미 "# EMPIRES"에 도달하기 훨씬 전에 새로운 행을 찾는 것을 중지합니다.

public String getEmpirestxt(String fileName) { 
    Scanner sc; 
    try { 
     sc = new Scanner(new File(fileName)); 
     String currentLine = sc.nextLine(); 
     StringBuilder empiresText = new StringBuilder(currentLine); 
     while (!currentLine.startsWith("# EMPIRES")) { 
      currentLine = sc.nextLine(); 
      System.out.println(currentLine); 
     } 
     currentLine = sc.nextLine(); 
     while (sc.hasNextLine() && currentLine.charAt(0)!='#') { 
      empiresText.append("\n").append(sc.nextLine()); 
     } 
     return empiresText.toString(); 
    } catch (FileNotFoundException ex) { 
     System.out.println("Landed_Titles.txt not found."); 
    } 
    return null; 
} 

TEXTFILE 자체 : https://www.wetransfer.com/downloads/a1093792d5ac54b6ccce04afecb9357f20140402095042/505fca

+0

"currentLine = sc.nextLine();"을 주석 처리 할 수 ​​있습니까? 그리고 그것이 효과가 있는지보십시오. – Boris

+0

아무 것도 바뀌지 않기 때문에 첫 번째 루프에 갇혀있는 것보다 ... – BURNS

+1

[Java 스캐너가 전체 파일을 통과하지 못함] (http://stackoverflow.com/questions/8330695/java-scanner-not-going- 전체 파일 통과) –

답변

1

이 문제에 대한 나의 해결책이다 . 스캐너 대신 newBufferedReader를 사용하여 파일을 읽었습니다. 이 예는 방법의 정수는

public String getEmpirestxt2(String fileName) { 
    Charset charset = Charset.forName("ISO-8859-1"); 
    Path filePath = Paths.get(fileName); 
    try (BufferedReader reader = Files.newBufferedReader(filePath, charset)) { 
     String line = null; 

     // find the start of the piece 
     while ((line = reader.readLine()) != null && !line.equals(START)) { 
     } 
     System.out.println("START: " + line); 

     // getting the piece 
     StringBuilder sb = new StringBuilder(); 
     while ((line = reader.readLine()) != null && !line.startsWith(END)) { 
      sb.append(line); 
     } 
     System.out.println("END: " + line); 

     return sb.toString(); 
    } catch (IOException x) { 
     System.err.format("IOException: %s%n", x); 
    } 
    return null; 
} 

자바 7에서 작동은 다음과 같습니다

private static final String START = "# EMPIRES"; 
private static final String END = "#"; 

나는 당신의 파일을 테스트하고 그것을 잘 작동합니다. 다음과 같이 필요한 부분의 시작과 끝 지점을 인쇄합니다.

START: # EMPIRES 
END: #  color={ 144 80 60 } 
+0

코드가 THX처럼 작동합니다! :) 단지 나머지 질문 하나, 첫 번째 반복문에는 아무 것도 없습니다. 어떻게 영원한 반복문에 얽매이지 않게 될까요? – BURNS

+0

첫 번째 while 루프에서는 파일을 한 줄씩 읽습니다. 비어 있기 때문에 우리는 단순히이 줄을 무시합니다. 결국 리더는 START를 찾아 루프를 종료합니다. 이것은 반복을위한 조건입니다 :! line.equals (START). START를 누르면이 조건이 거짓으로되고 루프가 종료됩니다. – Boris

+0

그래서 while 제어 구조가 자동으로 다음 줄로 이동합니까? – BURNS

1
String currentLine = sc.nextLine(); 

당신은 다음 줄에서 읽기 시작하고있다.

+0

게시 한 코드에 오류가 없으므로 문제는 첫 번째 while 루프에 있습니다. – BURNS

+0

컴파일 시간 또는 런타임 오류가 없습니다. 이것은 논리적 오류입니다.nextline은 다음 줄에서 읽습니다. 그래서 처음에는 두번째 줄과 비교하고 있습니다 – stinepike

0

조건 :

while (sc.hasNextLine() && currentLine.charAt(0)!='#') 

때문에 두 번째 술어의 파일을 읽을 줄 이상이있는 경우에도 해지 할 수 있습니다. currentLine.charAt(0)!='#'fales이면 while 루프가 종료됩니다. 그렇다고해서 더 이상 읽을 줄이 없다는 의미는 아닙니다.

currentLine = sc.nextLine(); 
while (sc.hasNextLine() && currentLine.charAt(0)!='#') { 
    empiresText.append("\n").append(sc.nextLine()); 
} 

가 있어야한다 : 그렇지 않으면 라인

do{ 
    currentLine=sc.nextLine(); 
    empiresText.append("\n").append(sc.nextLine()); 
}while(sc.hasNextLine() && currentLine.charAt(0)!='#'); 

# 제국 읽을 수 없습니다 직후 및 루프 당신이 currentLine

이 부분을 설정하지 동안 초에서

0

currentLine이 업데이트되지 않기 때문에 코드 while 루프가 중단되지 않습니다. 두 번째의

+0

제 코드는 "# EMPIRES"가 시작되는 부분까지 도달 할 수 없기 때문에 해결책을 테스트 할 수 없습니다. – BURNS

0

추가] 대신 sc.nextLine의 currentLine() 루프 동안 :

while (sc.hasNextLine() && currentLine.charAt(0) != '#') { 
    empiresText.append("\n").append(currentLine); 
    currentLine = sc.nextLine(); 
} 

그렇지 않으면 아래처럼 하나의 루프를 사용할 수 있습니다 : 여기

while (sc.hasNextLine()){ 
    if(sc.nextLine().startsWith("# EMPIRES")){ 
     currentLine = sc.nextLine(); 
     while (sc.hasNextLine() && currentLine.charAt(0) != '#') { 
      empiresText.append("\n").append(currentLine); 
      currentLine = sc.nextLine(); 
     } 
    } 
} 
+0

마지막 행이'#EMPIRES'으로 시작한다면 어떨까요? 이 경우'sc.nextLine()'이 반환 할 내용은 무엇입니까? – Braj

+0

@ 리샤브 : 작동하지 않았고, 한 줄만 남았습니다. 첫 번째 코드 – BURNS

관련 문제