문자열이 있는지 텍스트 파일을 스캔하고, 찾은 경우 해당 문자열로 새 txt 파일을 만듭니다.

닉 롤린스

내가 뭘하려고하는 것은위한 TXT 파일을 검사하는 것입니다 그래서 String그이 경우, String발견, 새로운 TXT 파일의 요구를 생성하고는 String그것으로 writen. String의 이름에 - 수 - 검색 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();
  }
}

내가 시도한 것은 원래 텍스트 파일에서 문자열을 스캔하는 while-loop를 만들고 해당 문자열이 발견되면 txt 파일을 만들고 해당 문자열을 입력하는 것입니다.

현재 일어나고있는 것은 원본 파일이 스캔되지만 (System.out.println으로 테스트했습니다), 문자열이있는 새 파일 String은 원본 txt 파일에 있는지 여부에 관계없이 생성 됩니다.

안드레이 마 카레 비치

기본적으로 스캐너를 잘못된 방식으로 사용했습니다. 다음과 같이해야합니다.

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();

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관