2016-08-07 3 views
-2

스캐너를 사용하여 주어진 라인에서 파일 읽기를 시작합니다.스캐너를 사용하여 특정 라인에서 읽기 시작

두 번째 줄부터 파일 끝까지 읽고 첫 줄을 제외하고 싶습니다. 당신은 실제로 다음 파일의 첫 번째 N 라인을 건너 뛸 수있는 방법을 만들 수 있습니다 어떤 도움을 주시기 바랍니다

감사

+4

http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine() –

답변

0

가 "시동"값의 순간을 포착하는 부울를 사용 값을 읽기 시작합니다.

public static final int STARTER = "3"; 

public static void main(String[] args) { 
    boolean read = false; 
    try { 
     Scanner s = new Scanner(new File("input.txt")); 
     while (s.hasNextLine()) { 
      String line = s.nextLine(); 
      if (!read) { 
       if (Integer.parseInt(line) == STARTER) { 
        read = true; 
       } 
      } else { 
       System.out.println(line); // or save to a list or ... 
      } 
     } 
    } catch (Exception e){ 
     System.out.println(e); 
    } 
} 
+0

답변을 주셔서 감사합니다.이 코드는 동일한 코드에서 특정 라인을 제외하고 파일을 읽는 시간을 제외하려면이 라인에서 파일 읽기를 시작할 함수에 매개 변수로 라인을 보내야합니다. – Shaimaa

1

나는이 줄을 시도했지만 그것은

String line = input.next("pass the line that I want to start reading from"); 

작동하지 않습니다 파일을 정상적으로 읽으십시오.

import java.io.File; 
import java.util.Scanner; 

public class Main { 

    public static void main(String[] args) { 
     try { 
      Scanner s = new Scanner(new File("input.txt")); 
      skipLines(s, 3);//skip 3 lines of input.txt file 
      //read the rest of the file 
      while (s.hasNextLine()) { 
       String line = s.nextLine(); 
       // use lines here 
       System.out.println(line); 
      } 
     }catch (Exception e){ 
     } 
    } 

    public static void skipLines(Scanner s,int lineNum){ 
     for(int i = 0; i < lineNum;i++){ 
      if(s.hasNextLine())s.nextLine(); 
     } 
    } 
} 

를 Input.txt : 여기서

는 일례이다

1 
2 
3 
4 
5 
6 
7 
8 
9 
10 

출력 :

4 
5 
6 
7 
8 
9 
10 
+0

덕분에 당신은 환영 답변 – Shaimaa

+0

에 대한 많은 :) 하는 경우를 이 대답으로 해결 된 문제는 올바른 것으로 표시하십시오. –

관련 문제