In: Computer Science
2. Create a java program that reads a file line by line and extract the first word.
The program will ask for the name of input and output file.
Input file: words.txt
today tomorrow
sam peterson
peter small
roy pratt
Output file: outwords.txt
tomorrow
peterson
small
pratt
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class ExtractFirstWord {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter input file name: ");
File file = new File(in.nextLine());
try {
Scanner fin = new Scanner(file);
System.out.print("Enter output file name: ");
PrintWriter pw = new PrintWriter(in.nextLine());
String line, words[];
while (fin.hasNextLine()) {
line = fin.nextLine();
words = line.split(" ");
if (words.length > 1)
pw.println(words[1]);
}
pw.close();
fin.close();
} catch (FileNotFoundException e) {
System.out.println(file.getAbsolutePath() + " does not exists!");
}
}
}