Nik Rawlins
Nik Rawlins

Reputation: 133

Scan text file for a string, if found, create new txt file with that string

So what I am trying to do is to scan a txt-file for a String, if that String is found, a new txt-file needs to be created and the String writen into it. The String, the name of the to-be-searched txt-file and the txt-file that will/can be created will be all put in through the command line.

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

What I tried to do is create a while-loop that scans the original text file for a string, and if that string is found create a txt file and enter that string into it.

What is currently happening is that the original file is scanned (I tested that with System.out.println), but the new file with the string is created no matter if the String is in the original txt-file or not.

Upvotes: 1

Views: 124

Answers (1)

Andrei Makarevich
Andrei Makarevich

Reputation: 444

Basically, you have just used scanner in wrong way. You need to do that in this way:

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

Upvotes: 0

Related Questions