繁体   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