My prof posted this to practice exception handling and reading and writing to textfiles:
Write a method called removeFirstWord
removeFirstWord
returns an int and takes two strings as arguments.
The first argument is the name of the input file and the second the name of the output file.
It reads the input file as a text file one line at the time. It removed the first word from each line and write the resulting line to the output file. sometext.txt below is an example input file with output.txt the expected output file.
If the input file does not exist, the method should throw FileNotFoundException. If the input file is empty, the method should throw EmptyFileException. The method should not throw any other exceptions.
If an exception other than FileNotFoundException
is thrown, the method should return -1. Otherwise, the method returns 0."
This was his code:
public static int removeFirstWord(String inputFilename, String outputFilename) throws FileNotFoundException, EmptyFileException {
int lineCounter = 0;
try {
BufferedReader input = new BufferedReader(new FileReader(inputFilename));
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(outputFilename)));
String line = input.readLine();
while (line!=null){
lineCounter++;
String[] words = line.split(" ");
for (int index = 1; index < words.length; index++) {
String word = words[index];
writer.print(word + " ");
}
writer.println();
line = input.readLine();
}
writer.flush();
writer.close();
input.close();
} catch (IOException ioe) {
return -1;
}
if (lineCounter == 0) {
throw new EmptyFileException();
}
return 0;
}
I do not understand why she used an array. Can't you just read the first word and stop at a space and write that word to the output file and jump to the next line?
Also I do not understand the difference between doing a throws FileNotFoundException
, EmptyFileException
vs just doing a catch?