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