/**
 * Counts all unique words shared between two files and outputs the words that
 * are found to a new file. Words are output to a file named output.txt in the
 * working directory. If output.txt exists, it is overwritten. If either file
 * is empty, returns 0. Words are defined as nonempty groups of characters split
 * by newline or space characters.
 *
 * @param file1 The first file that is being read from. Cannot be null
 * @param file2 The second file that is being read from. Cannot be null
 * @return The number of unique words in common between file1 and file2.
 * @throws FileNotFoundException if the given file does not exist
 * @throws IOException if the file cannot be read
 */
static long wordsInCommon(File file1, File file2) throws FileNotFoundException, IOException {
	Scanner s = new Scanner(file1); 
	Scanner s2 = new Scanner(file2);

	// Find and store all unique words in file 1
	HashSet<String> f1words = new HashSet<String>();
	while (s.hasNextLine()) {
		String line = s.nextLine();
		for (String i : line.split(" ")) {
			f1words.add(i);
		}
	}

	// Find and store all unique words in file 2 also in file 1
	HashSet<String> sameWords = new HashSet<String>();
	while (s2.hasNextLine()) {
		String line = s2.nextLine();
		for (String i : line.split(" ")) {
			if(f1words.contains(i)){
				sameWords.add(i);
			}
		}
	}

	File f3 = new File("output.txt");
	FileWriter writer = new FileWriter(f3);
	writer.write(sameWords.toString());
	writer.close();
	return sameWords.size();
}