java 文件读取汇总

概要说明:这里汇总了线上常用到的各种按行读取方法

1、BufferedReader

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
 
public class ReadFileLineByLineUsingBufferedReader {
 
    public static void main(String[] args) {
        BufferedReader reader;
        try {
            reader = new BufferedReader(new FileReader("/Users/test/Downloads/myfile.txt"));
            String line = reader.readLine();
            while (line != null) {
                System.out.println(line);
                // read next line
                line = reader.readLine();
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2、Scanner

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
 
public class ReadFileLineByLineUsingScanner {
 
    public static void main(String[] args) {
        try {
            Scanner scanner = new Scanner(new File("/Users/test/Downloads/myfile.txt"));
            while (scanner.hasNextLine()) {
                System.out.println(scanner.nextLine());
            }
            scanner.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

3、Files

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
 
public class ReadFileLineByLineUsingFiles {
 
    public static void main(String[] args) {
        try {
            List<String> allLines = Files.readAllLines(Paths.get("/Users/test/Downloads/myfile.txt"));
            for (String line : allLines) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

4、RandomAccessFile

import java.io.IOException;
import java.io.RandomAccessFile;
 
public class ReadFileLineByLineUsingRandomAccessFile {
 
    public static void main(String[] args) {
        try {
            RandomAccessFile file = new RandomAccessFile("/Users/test/Downloads/myfile.txt", "r");
            String str;
            while ((str = file.readLine()) != null) {
                System.out.println(str);
            }
            file.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

posted @ 2021-05-19 23:47  星火燎原智勇  阅读(107)  评论(0编辑  收藏  举报