Java多种读文件方式

3,222 阅读1分钟

平时做一些小工具,小脚本经常需要对文件进行读写操作。早先记录过Java的多种写文件方式:juejin.cn/post/684490…

这里记录下多种读文件方式:

  • FileReader
  • BufferedReader: 提供快速的读文件能力
  • Scanner:提供解析文件的能力
  • Files 工具类

BufferedReader

构造的时候可以指定buffer的大小

BufferedReader in = new BufferedReader(Reader in, int size);
    public static void main(String[] args) throws IOException {
        String file = "C:\\Users\\aihe\\Desktop\\package\\2019.08\\tmp\\register.txt";
        BufferedReader reader = new BufferedReader(new FileReader(file));
        String st;
        while ((st = reader.readLine()) != null){

        }
        reader.close();
    }

FileReader

用于读取字符文件。直接用一下别人的demo

// Java Program to illustrate reading from 
// FileReader using FileReader 
import java.io.*; 
public class ReadingFromFile 
{ 
public static void main(String[] args) throws Exception 
{ 
	// pass the path to the file as a parameter 
	FileReader fr = 
	new FileReader("C:\\Users\\pankaj\\Desktop\\test.txt"); 

	int i; 
	while ((i=fr.read()) != -1) 
	System.out.print((char) i); 
} 
} 

Scanner

读取文件的时候,可以自定义分隔符,默认分隔符是

public static void main(String[] args) throws IOException {
        String file = "C:\\Users\\aihe\\Desktop\\package\\2019.08\\tmp\\register.txt";
        Scanner reader = new Scanner(new File(file));
        String st;
        while ((st = reader.nextLine()) != null){
            System.out.println(st);
            if (!reader.hasNextLine()){
                break;
            }
        }
        reader.close();
    }

指定分隔符:

Scanner sc = new Scanner(file); 
sc.useDelimiter("\\Z"); 

Files

读取文件作为List

    public static void main(String[] args) throws IOException {
        String file = "C:\\Users\\aihe\\Desktop\\package\\2019.08\\tmp\\register.txt";
        List<String> lines = Files.readAllLines(new File(file).toPath());
        for (String line : lines) {
            System.out.println(line);
        }
    }

读取文件作为String

  public static void main(String[] args) throws IOException {
        String file = "C:\\Users\\aihe\\Desktop\\package\\2019.08\\tmp\\register.txt";
        byte[] allBytes = Files.readAllBytes(new File(file).toPath());
        System.out.println(new String(allBytes));
    }

最后

这是几种常见的读文件方式