平時作一些小工具,小腳本常常須要對文件進行讀寫操做。早先記錄過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