从文本文件中读取一行

Abh*_*nty -1 java 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);
        }

        }

    }
Run Code Online (Sandbox Code Playgroud)

经过调试,这就是我得到的,

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
Run Code Online (Sandbox Code Playgroud)

以上两行是:

  1. 变量fr被初始化.
  2. while循环.

kil*_*joy 5

您遇到这些错误,因为您调用的方法和构造函数抛出异常.这些要么需要使用try/catch块捕获,要么在方法签名中声明.

这些错误是编译时错误,而不是运行时.它并不是说该文件不存在,而是需要捕获异常以防万一.

Oracle教程