Java读取文件

时间:2017-11-02 02:25:57

标签: java

我正在尝试学习文件读取和写入,但我尝试使用BufferedReader和Scanner,它将始终显示异常消息。我按照书中的步骤进行操作。不确定出了什么问题。

package fileIO;

import java.io.*;

import java.util.*;

public class files {

    public static void main(String[] args) {
        String line = "";
        BufferedReader br = null;
        try{
            br = new BufferedReader(new FileReader("Shadow.txt"));
            while(br.readLine() != null){
                line += br.readLine();
                System.out.println(line);
            }


        }catch(FileNotFoundException e){
            System.err.println("File not found");
        }catch(Exception e){
            System.out.println("Throwing exception");
        }
    }
}

2 个答案:

答案 0 :(得分:1)

稍稍更改while

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

答案 1 :(得分:0)

这对我有用:

import java.io.*;

class Test {
    public static void main(String[] args) {
        Printer.print("Shadow.txt");
    }
}

public class Printer {
    public static void print(String filename) {
        String line;
        try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
            while ((line = br.readLine()) != null) System.out.println(line);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            System.out.close();
        }
    }
}  

我将您升级为try-with-resources,并修复了while循环。希望它也是如何编写更多模块化代码的一个例子。