从文本文件中读取一行

时间:2017-05-09 06:49:14

标签: 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);
        }

        }

    }

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

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循环。

5 个答案:

答案 0 :(得分:5)

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

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

Oracle Tutorial

答案 1 :(得分:0)

请输入驱动器的完整路径以及文件夹位置。

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

喜欢这个。它应该像在资源管理器中复制粘贴一样,您可以直接跳转到该文件。

如果使用MAC,请右键单击文本文件和属性,然后复制该位置并将其粘贴到您的代码中。

答案 2 :(得分:0)

在您的代码中,下面的行需要捕获

$_GET['id']

使用try-catch块或抛出异常来处理它。

答案 3 :(得分:0)

print(val['name'])
'test1'
'test2'

您需要处理读者生成的异常

答案 4 :(得分:0)

您的文件路径应包含整个路径,例如:

"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();
}
相关问题