Java多種讀檔案方式
阿新 • • 發佈:2019-12-31
平時做一些小工具,小指令碼經常需要對檔案進行讀寫操作。早先記錄過Java的多種寫檔案方式:juejin.im/post/5c997a…
這裡記錄下多種讀檔案方式:
- 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));
}
複製程式碼
最後
這是幾種常見的讀檔案方式