Java多種讀文件方式

平時作一些小工具,小腳本常常須要對文件進行讀寫操做。早先記錄過Java的多種寫文件方式:juejin.im/post/5c997a…java

這裏記錄下多種讀文件方式:bash

  • 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

用於讀取字符文件。直接用一下別人的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); 
} 
} 
複製代碼

Scanner

讀取文件的時候,能夠自定義分隔符,默認分隔符是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"); 
複製代碼

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));
    }
複製代碼

最後

這是幾種常見的讀文件方式3d

相關文章
相關標籤/搜索