import java.io.FileReader; import java.io.BufferedReader; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; import javax.swing.JFileChooser; public class Message { // Displays a dialog box for selecting a file, returning a ByteScanner // corresponding to the selected file. Canceling the dialog terminates // the program. public static BufferedReader promptUser(String prompt) { JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle(prompt); int result = chooser.showDialog(null, prompt); if(result != JFileChooser.APPROVE_OPTION) { // dialog canceled System.err.println("File selection canceled; program complete"); System.exit(0); return null; // should never happen } try { return new BufferedReader(new FileReader(chooser.getSelectedFile())); } catch(IOException e) { System.err.println("Error opening file; program complete"); System.exit(0); return null; // should never happen } } // Reads the next message from the indicated source, returning a // Message object encapsulating its important information. // If the end of file has been reached, the method returns null. public static Message readNext(BufferedReader in) { try { List words = new ArrayList(); while(true) { String line = in.readLine(); if(line == null) return null; Scanner sc = new Scanner(line); if(line.startsWith("ID:")) { sc.next(); // skip past "ID:" int id = sc.nextInt(); boolean isSpam = sc.next().equals("spam"); return new Message(id, words, isSpam); } else { while(sc.hasNext()) { words.add(sc.next()); } } } } catch(IOException e) { return null; } } private int id; private List words; private boolean isSpam; // Constructs a Message including the indicated information private Message(int id, List words, boolean isSpam) { this.id = id; this.words = Collections.unmodifiableList(words); this.isSpam = isSpam; } // Returns the identifying number for this message. public int getId() { return id; } // Returns a list of all words found in this message. public List getWords() { return words; } // Returns true if this message has been marked as spam. public boolean isSpam() { return isSpam; } }