簡體   English   中英

從文本文件中讀取一行

[英]Reading a line from a text file

我正在嘗試從文本文件中讀取一行,但是程序不斷返回錯誤,指出無法找到文件名。 關於如何解決問題的任何想法。

源代碼:

import java.io.FileReader;
import java.io.BufferedReader;

public class Cipher {

    public String file_name;

    public Cipher(){
        file_name = "/Users/SubrataMohanty/IdeaProjects/CaesarCipher/src/cipher_text.txt";

    }

    public static void main(String[] args) {

        BufferedReader br = null;
        FileReader fr = null;

        Cipher cipher_1 = new Cipher();


        fr = new FileReader(cipher_1.file_name);
        br = new BufferedReader(fr);

        String current_line;

        while ((current_line = br.readLine()) != null){
            System.out.println(current_line);
        }

        }

    }

經過調試,這就是我得到的,

Error:(25, 14) java: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
Error:(30, 43) java: unreported exception java.io.IOException; must be caught or declared to be thrown

以上兩行是:

  1. 變量fr被初始化。
  2. while循環。

之所以會出現這些錯誤,是因為您調用的方法和構造函數會引發異常。 這些要么需要用try / catch塊捕獲,要么在方法簽名中聲明。

這些錯誤是編譯時錯誤,而不是運行時。 這並不是說文件不存在,而是您需要捕獲一個例外,以防萬一。

Oracle教程

請輸入完整的路徑,即驅動器以及文件夾位置。

C:\....\Users/SubrataMohanty/IdeaProjects/CaesarCipher/src/cipher_text.txt

像這樣。 就像在資源管理器中復制粘貼時,您可以直接跳到該文件。

如果使用MAC,則右鍵單擊文本文件和屬性,然后復制位置並將其粘貼到代碼中。

在您的代碼中,以下幾行需要捕獲

  fr = new FileReader(cipher_1.file_name);
  br = new BufferedReader(fr);

使用try-catch塊或引發Exception來處理它。

try{  
        fr = new FileReader(cipher_1.file_name);
        br = new BufferedReader(fr);

        String current_line;

        while ((current_line = br.readLine()) != null){
            System.out.println(current_line);
}catch(Exception e)
        e.printStackTrace();
{

您需要處理讀者產生的異常

您的文件路徑應包括完整路徑,例如:

"C:\\Users\\John Doe\\Desktop\\Impactor_0.9.41.txt"

請注意,我使用了一個額外的'\\',但不確定是否很重要,但是我總是這樣做。

同樣為了清楚起見,您也可以像這樣更改br和fr,但是您所做的也很好。 但是重要的是在try-catch塊中打開文件,如下所示:

try{
    br = new BufferedReader(new FileReader(cipher1.file_name));
} catch(FileNotFoundException e){
    e.printStackTrace();
}

另外,在讀取和打印文件到控制台時,將其放入try catch中:

try{
    String current_line;
    while((current_line = br.readLine()) != null){
        System.out.println(current_line);
        current_line = br.readLine();
    }
} catch(IOException e){
    e.printStackTrace();
}

暫無
暫無

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

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