簡體   English   中英

Java:如何從文本文件的每一行中提取第一個單詞並將其寫入新的文本文件?

[英]Java: How to take the first word in each line from a text file and write it to a new text file?

我的教授將其發布為練習異常處理以及讀寫文本文件:

寫一個叫做removeFirstWord的方法

removeFirstWord返回一個int並接受兩個字符串作為參數。

第一個參數是輸入文件的名稱,第二個參數是輸出文件的名稱。

它一次將輸入文件讀取為文本文件。 它從每一行中刪除了第一個單詞,並將結果行寫入輸出文件。 下面的sometext.txt是示例輸入文件,而output.txt是預期的輸出文件。

如果輸入文件不存在,則該方法應引發FileNotFoundException。 如果輸入文件為空,則該方法應引發EmptyFileException。 該方法不應引發任何其他異常。

如果拋出FileNotFoundException以外的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與僅僅進行捕捉之間的區別嗎?

第一件事首先-實際上,您對她的要求有點困惑。 實際上,她只想從給定的文本文件中刪除所有行的所有第一個單詞,而其余單詞將保留在輸出文件中。 因此,為此,她選擇將完整的行轉換為String數組。 另一種可能的方法是對給定的行進行子串處理,但這會增加時間復雜度。

第二個原因是她使用throw代替catch塊,因為根據業務需求,沒有用來捕獲這兩個異常,她想稍后捕獲它,或者想將其顯示給最終用戶。

我認為這會幫助您。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM