2017-01-22 1 views
1

그래서 내가 수행하려고하는 작업은 String의 txt 파일을 스캔하는 것입니다. String이 발견되면 새 txt 파일이 필요합니다. 생성되고 그것에 String 서면. String, 검색 할 txt 파일의 이름과 만들거나 만들 수있는 txt 파일은 모두 명령 줄을 통해 입력됩니다. 내가 할 노력은 무엇문자열이있는 경우 텍스트 파일을 검색하여 문자열이 포함 된 새 txt 파일을 만듭니다.

public class FileOperations { 
 

 
    public static void main(String[] args) throws FileNotFoundException { 
 
    String searchTerm = args[0]; 
 
    String fileName1 = args[1]; 
 
    String fileName2 = args[2]; 
 
    File file = new File(fileName1); 
 
    Scanner scan = new Scanner(file); 
 

 
    while (scan.hasNextLine()) { 
 
     if (searchTerm != null) { 
 
     try { 
 
      BufferedWriter bw = null; 
 
      bw = Files.newBufferedWriter(Paths.get(fileName2), StandardOpenOption.CREATE, StandardOpenOption.APPEND); 
 
      bw.write(searchTerm); 
 
      bw.close(); 
 
     } catch (IOException ioe) { 
 
      ioe.printStackTrace(); 
 
     } 
 

 

 
     } 
 
     scan.nextLine(); 
 
    } 
 
    scan.close(); 
 
    } 
 
}

문자열의 원래 텍스트 파일을 스캔 동안 루프를 생성하고, 해당 문자열이 txt 파일을 만들고 그것으로 그 문자열을 입력 발견되면 .

원래 파일이 스캔되었지만 (System.out.println을 사용하여 테스트 했음) String이 원본 txt 파일에 있는지 여부에 관계없이 문자열이있는 새 파일이 만들어집니다. .

답변

0

기본적으로 잘못된 방식으로 스캐너를 사용했습니다. 당신은이 방법으로이 작업을 수행해야합니다

String searchTerm = args[0]; 
String fileName1 = args[1]; 
String fileName2 = args[2]; 
File file = new File(fileName1); 

Scanner scan = new Scanner(file); 
if (searchTerm != null) { // don't even start if searchTerm is null 
    while (scan.hasNextLine()) { 
     String scanned = scan.nextLine(); // you need to use scan.nextLine() like this 
     if (scanned.contains(searchTerm)) { // check if scanned line contains the string you need 
      try { 
       BufferedWriter bw = Files.newBufferedWriter(Paths.get(fileName2)); 
       bw.write(searchTerm); 
       bw.close(); 
       break; // to stop looping when have already found the string 
      } catch (IOException ioe) { 
       ioe.printStackTrace(); 
      } 
     } 
    } 
} 
scan.close(); 
+0

나는 실제로 한'문자열 스캔 = scan.nextLine를(); 편집 및 그것을 실현하지 않으면 서'가 어떤 시점에서, 나는 그것을 삭제해야합니다. 정말 고마워요. 이제 효과가 있었고 훨씬 더 의미가 있습니다! –

관련 문제