2017-01-24 3 views
1

왜 내 Java 서블릿이 멈추는 지 알 수 있습니까? 컴파일하지만 CPU가 100 %로 이동하므로 어딘가에 무한 루프가 있다고 가정하고 있습니다.?Java에서 파일 무한 루프 읽기

quotes.txt에는 10 줄만 있습니다. scan.nextLine() 첫 번째 루프에서 호출되지 않기 때문에

String line = ""; 
try { 

    String filePath = new File("").getAbsolutePath(); 
    filePath += "/quotes.txt"; 
    Scanner scan = new Scanner(filePath); 

    int lines = 0; 
    while (scan.hasNextLine()) { 
     lines++; 
    } 

    Random random = new Random(); 
    int randomInt = random.nextInt(lines); 

    for (int i = 0; i < randomInt; i++) { 
    line = scan.nextLine(); 
    } 

    scan.close(); 

    } catch (Exception e){ 
     line = e.getMessage(); 
    } 

감사

+2

귀하의 while 루프 검사 읽고 그 다음 줄 –

+1

'(scan.hasNextLine())'동안 - 당신이 루프에서 스캐너에서 읽어 본 적이. 그래서 한 줄이라도 있다면 "영원히"다음 줄을 사용할 수 있습니다. – David

+0

@ A.A. 첫 번째 루프는 라인을 계산하여 두 번째 루프는 실제로 파일에있는 임의의 수의 라인 만 선택합니다. –

답변

0

코드가 중단됩니다. 구현 한 경우에도 두 번째 루프 (for 루프)는 스캐너에서 파일의 입력이 없기 때문에 예외가 발생합니다.

Scanner 개체를 다시 초기화하지 않아도됩니다.

try { 

    String filePath = new File("").getAbsolutePath(); 
    filePath += "/quotes.txt"; 

    List<String> listOfLines = Files.readAllLines(Paths.get(filePath), Charset.defaultCharset()); 

    Random random = new Random(); 
    int randomInt = random.nextInt(listOfLines.size()); 

    System.out.println(listOfLines.get(randomInt)); 

} catch (IOException e) { 
    e.getMessage(); 
} 

이제 위의 코드 (이 솔루션은 분명히 것은 아니다 메모리에 모든 줄을 읽습니다 당신은 내가 다음을 제안 파일에서 (순서에 상관없이) 임의의 줄을 싶어하기 때문에

대용량 파일의 경우), 난수를 가져 와서 줄을 표시 할 수 있습니다.

당신은 또한 당신이 스캐너 생성자에서 문자열을 전달하는 this SO Question

0

안녕 볼 수 있습니다. 당신은 당신이

while(sc.hasNextLine()){ 
line= sc.nextLine();} 

이 의지를 사용할 수 있습니다 왜 당신은 당신이 파일 에서 읽고 싶은 경우 무작위로 다시 루프를 사용하는 이유 라인을 계산하는 카운터를 사용하는 경우

Scanner sc = new Scanner(new File(filepath)); 

를 사용할 필요가 마지막 줄 줘.

EDIT 파일에서 임의의 줄을 가져 오려면. 커서가

int count=0; 
List<String> lines = new ArrayList<>(); 
while(sc.hasNextLine()){ 
    line= sc.nextLine(); 
    lines.add(line); 
    count++; 
} 
Random rand = new Random(); 
int n= rand.nextInt(count); 
String output = lines.get(n); 
+0

마지막 줄이 아닌 임의의 줄을 얻으려고합니다. –

+0

루프가 입력 스트림을 전달해야하며 문자열을 전달하는 좋은 스캐너입니다. – Manoj

0

HasNextLine 다음 값으로 이동하지 않는 while 루프에서 파일의 끝으로 이동 그래서 이동하는 꽵를 사용합니다. 변수를 사용하려면 변수에 할당 할 수도 있습니다. 그 다음 줄은 없지만 않을 경우

ArrayList<String> a = new Arraylist<String>(); 
    while (scan.hasNextLine()) { 
    a.add(scanner.nextLine()); 
    } 
    Random random = new Random(); 
    int randomInt = random.nextInt(a.size()); 
    line = a.get(randomInt);