读/写文件时处理异常

时间:2015-03-23 15:30:58

标签: java

我正在尝试从一个文件中读取,但我只是不知道如何在使用try catch块的时候这样做...如果发生了一些不好的事情,怎么能让它抛出异常,但如果没关系执行这一行:br.readLine()?它只是说br没有被宣布。如果我需要在不同的地方使用“br”和“bw”(比如不同的方法)怎么办?我是否必须在那里申报?

try {
    BufferedReader br = new BufferedReader(new FileReader(file));
    BufferedWriter bw = new BufferedWriter(new FileWriter(file));
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

br.readLine();

3 个答案:

答案 0 :(得分:0)

br在try的范围内声明,因此在catch之后消失了。你想这样做:

BufferedReader br = null;
BufferedWriter bw = null;
try {
    br = new BufferedReader(new FileReader(file));
    bw = new BufferedWriter(new FileWriter(file));
} catch (IOException e) {
    e.printStackTrace();
}
br.readLine();

注意你在catch之后冒空指针的风险,所以另一个选择是将br.readLine()写入try中,如下所示:

try {
    BufferedReader br = new BufferedReader(new FileReader(file));
    BufferedWriter bw = new BufferedWriter(new FileWriter(file));
    br.readLine();
} catch (IOException e) {
    e.printStackTrace();
}

答案 1 :(得分:0)

BufferedReader and BufferedWriter should be define outside from try and catch block than only we can access them outside
Try this code, it should work


     BufferedReader br = null;
             BufferedWriter bw =null;
             try {
                  br = new BufferedReader(new FileReader(file));
                  bw = new BufferedWriter(new FileWriter(file));
             } catch (IOException e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
             }
br.readLine();

答案 2 :(得分:0)

您已在try块中声明了BufferedReader和BufferredWriter,并在try和catch之外调用了br.readline(),因此它不知道br的声明位置。我有与上面相同的答案。

try {
BufferedReader br = new BufferedReader(new FileReader(new File ("path_to_your_file_to read")));
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("path_to_your_file_to_write")));
br.readLine();
} catch (IOException e) {
e.printStackTrace();
}