내가 뭘하려고하는 것은위한 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] 삭제
몇 마디 만하겠습니다