【问题标题】:Java: How to take the first word in each line from a text file and write it to a new text file?Java:如何从文本文件中获取每行中的第一个单词并将其写入新的文本文件?
【发布时间】: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;   
}

我不明白她为什么使用数组。您不能只读取第一个单词并停在一个空格处,然后将该单词写入输出文件并跳转到下一行吗? 另外,我不明白投掷 FileNotFoundExceptionEmptyFileException 与仅抓捕之间的区别?

【问题讨论】:

  • 鉴于代码已经解决了问题,您的问题可能更适合我们的姐妹网站Code Review Stack Exchange
  • 这是 Code Review Stack Exchange 的题外话。

标签: java exception-handling try-catch throws


【解决方案1】:

第一件事-实际上,您对她的要求有点困惑。实际上,她只想从给定的文本文件中删除所有行的所有第一个单词,并且剩余的单词将在输出文件中。 因此,为此她选择将整行转换为字符串数组。另一种可能的方法是对给定的行进行子串化,但这在时间复杂度上会很昂贵。

她使用 throws 而不是 catch 块的第二个原因,因为根据业务需求,捕获这两个异常是没有用的,她想稍后再捕获它或想将其显示给最终用户。

我想这会对你有所帮助。

【讨论】:

    猜你喜欢
    • 2012-06-08
    • 2019-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-23
    • 2014-10-18
    • 2019-07-07
    相关资源
    最近更新 更多