// This program is an example of file processing. // It takes in a search string that we use to // to search through the files in a list of the // top 250 movies on IMDB. // // If it finds the search string in the title of a // movie, it prints out some data to a file, in // tab separated format. // // This is version will find all the lines // in the input file that match the search string, // not just the first. import java.util.*; import java.io.*; public class Imdb3 { public static void main(String[] args) throws FileNotFoundException { Scanner console = new Scanner(System.in); Scanner input = new Scanner(new File("imdb.txt")); System.out.print("Type in a search string: "); String search = console.next(); System.out.print("Type in an output filename: "); String outputFile = console.next(); // creating a PrintStream creates the file if it doesn't // exist, or overwrites if it already existed PrintStream output = new PrintStream(new File(outputFile)); // find the movie, print out the header line, and the // line from the data file, to the output file String line = findMovie(input, search); if (line.length() > 0) { output.println("Rank\tVotes\tRating\tTitle"); // We know we found one movie already, with the // given if test above. continue printing out lines // as long as findMovie keeps finding them. do { display(line, output); line = findMovie(input, search); } while (line.length() > 0); } else { // going to system.out and not the output file // because it's helpful info to the user, not helpful in the data file System.out.println("Movie not found"); } } // returns the next line from the input that contains the given searchText, // or "" if no matching line was found. Note that this method // takes advantage of the Scanner's cursor position, even across // multiple successive calls to this method. public static String findMovie(Scanner input, String searchText) { while (input.hasNextLine()) { String line = input.nextLine(); if (line.toLowerCase().contains(searchText.toLowerCase())) { return line; } } return ""; } // outputs a line from the Imdb file, separating the columns by tabs. public static void display(String line, PrintStream output) { Scanner lineScan = new Scanner(line); int rank = lineScan.nextInt(); int votes = lineScan.nextInt(); double rating = lineScan.nextDouble(); String title = lineScan.next(); while (lineScan.hasNext()) { title += " " + lineScan.next(); } output.println(rank + "\t" + votes + "\t" + rating + "\t" + title); } }