平时做一些小工具,小脚本经常需要对文件进行读写操作。早先记录过Java的多种写文件方式: juejin.im/post/5c997a…
这里记录下多种读文件方式:
构造的时候可以指定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(); } 复制代码
用于读取字符文件。直接用一下别人的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); } } 复制代码
读取文件的时候,可以自定义分隔符, 默认分隔符是
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"); 复制代码
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); } } 复制代码