2014-06-10 1 views
0
public static void main(String ar[]) throws FileNotFoundException{ 
    scan = new Scanner(new FileReader(new File("files.txt"))); 
    String nextLine = scan.nextLine(); 
    String[] fileNames = nextLine.split("\\s+"); 

    for(int i=0;i<fileNames.length;i++){ 
     System.out.println(fileNames[i]); 
    } 


    for(int i=0;i<nextLine.length();i++){ 
     char c = nextLine.charAt(i); 
     boolean isWhiteSpace = isWhiteSpace(c); 
     if(isWhiteSpace){ 
      if(c == ' ') 
       System.out.println("white space (blank) at index "+i); 
      if(c == '\n') 
       System.out.println("white space (line feed) at index "+i); 
      if(c == '\r') 
       System.out.println("white space (\\r - carriage return) at index "+i); 
      if(c == '\t') 
       System.out.println("white space (\\t - tab) at index "+i); 
     } 
    } 

} 

이 문제를 해결하는 데 도움이 필요합니다. 분명히 내 프로그램은 파일의 첫 번째 줄만 인식합니다.이 줄은 내용의 전체 파일을 읽어야합니다.전체 파일 대신 한 줄만 읽는 프로그램

변경하려면 어떤 변경이 필요합니까? 감사.

+4

왜 전체 콘텐츠를 읽어야한다고 생각하십니까? –

답변

3

글쎄,이 경우에만 파일에서 한 줄을 읽고 있기 때문이다 : 당신은 당신이 파일의 끝에 도달 할 때까지() scan.nextLine를 호출 할 필요가 전체 파일을 읽기 위해서는

scan = new Scanner(new FileReader(new File("files.txt"))); 
String nextLine = scan.nextLine(); 

. 파일의 끝을 확인하려면 while 루프를하고, 따라서 전체 파일을 통해 갈 수 있습니다

Scanner input = new Scanner(new File("\""+filename+"\"")); 
while(input.hasNextLine()) 
{ 
    String data = input.nextLine(); 
    //Do what you want with one line which is at each iteration stored in data 
} 
+0

방금 ​​시도했지만 대신 끝없는 While 루프로 들어갑니다. – user1769881

+0

@ user1769881 제대로 입력 했습니까? 이것은 무한 루프를 초래해서는 안됩니다 ... –

+0

죄송합니다, 그것이 효과가있다! 엄청 고마워! – user1769881

0

는 한 번만 String nextLine = scan.nextLine();를 사용하는 것처럼 보였다!

0

문자열 nextLine = scan.nextLine();

내게는 스캐너에서 "스캔"을 사용하여 파일에서 한 줄만 수락하는 것 같습니다. 따라서 문제의 파일에서 한 줄만 표시됩니다.

0

nextLine() 메서드를 한 번만 호출하므로 프로그램에서 한 줄만 읽을 수 있습니다. 사용 가능한 모든 행을 계속 읽으려면 for 루프를 추가해야합니다.

관련 문제