当先锋百科网

首页 1 2 3 4 5 6 7
public class Example {

    public static void main(String[] args) {
        Path path = Paths.get("/file/path");
        readWay1(path);
        readWay2(path);
        readWay3(path);
    }

    private static void readWay1(Path path) {
        try (
                BufferedReader bufferedReader = Files.newBufferedReader(path);
        ) {
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void readWay2(Path path) {
        try {
            List<String> lines = Files.readAllLines(path);
            lines.forEach(System.out::println);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void readWay3(Path path) {
        try {
            Stream<String> lines = Files.lines(path);
            lines.forEach(System.out::println);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}