【发布时间】:2018-09-14 18:24:42
【问题描述】:
我的教授发布了这个来练习异常处理和对文本文件的读写:
编写一个名为removeFirstWord的方法
removeFirstWord 返回一个 int 并接受两个字符串作为参数。
第一个参数是输入文件的名称,第二个参数是文件名 输出文件。
它每次将输入文件作为文本文件读取一行。它从每一行中删除了第一个单词并将结果行写入输出文件。下面的 sometext.txt 是一个示例输入文件,其中 output.txt 是预期的输出文件。
如果输入文件不存在,该方法应该抛出 FileNotFoundException。如果输入文件为空,则该方法应抛出 EmptyFileException。该方法不应抛出任何其他异常。
如果抛出FileNotFoundException 以外的异常,该方法应返回-1。否则,该方法返回 0。”
这是他的代码:
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;
}
我不明白她为什么使用数组。您不能只读取第一个单词并停在一个空格处,然后将该单词写入输出文件并跳转到下一行吗?
另外,我不明白投掷 FileNotFoundException、EmptyFileException 与仅抓捕之间的区别?
【问题讨论】:
-
鉴于代码已经解决了问题,您的问题可能更适合我们的姐妹网站Code Review Stack Exchange。
-
这是 Code Review Stack Exchange 的题外话。
标签: java exception-handling try-catch throws