Do some small tools at ordinary times, small scripts often need to read and write files. Earlier, I documented several ways to write files in Java: juejin.cn/post/684490…

Here are several ways to read a file:

  • FileReader
  • BufferedReader: Provides fast file reading capability
  • Scanner: Provides the ability to parse files
  • Files tools

BufferedReader

You can specify the size of the buffer when constructing it

BufferedReader in = new BufferedReader(Reader in, int size);
Copy the code
    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(); }Copy the code

FileReader

Used to read character files. Just use someone else’s 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); 
} 
} 
Copy the code

Scanner

When reading files, you can customize the delimiter. The default delimiter is

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();
    }
Copy the code

Specify the delimiter:

Scanner sc = new Scanner(file); 
sc.useDelimiter("\\Z"); 
Copy the code

Files

Read the file as 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); }}Copy the code

Read the file as 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));
    }
Copy the code

The last

These are common ways to read files