Java How to read a file

摘要: In Java, there are few ways to read a file.

In Java, there are few ways to read a file.

1. Java 8 – Files.lines, it will return a Stream

	//@Since 1.8
	Stream<String> lines = Files.lines(Paths.get("app.log"));
	List<String> content = lines.collect(Collectors.toList());

2. Java 7 – Files.readAllBytes or Files.readAllLines

	//@Since 1.7
	// Returns a byte[]
	byte[] bytes = Files.readAllBytes(Paths.get("app.log"));
	String content = new String(bytes);
	// Returns a List String
	List<String> content = Files.readAllLines(Paths.get("app.log"));

3. And this classic BufferedReader

	try (FileReader reader = new FileReader("app.log");
		BufferedReader br = new BufferedReader(reader)) {
		// read line by line
		String line;
		while ((line = br.readLine()) != null) {
			System.out.println(line);
     } catch (IOException e) {
            //e

1. Files.lines

In Java 8, we can use Files.lines to read a file into a Stream, it will close the resources (opened file) automatically.

app.log
Line 1
Line 2
Line 3
Line 4
Line 5

@FileExample1.java

package com.mkyong;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class FileExample1 {
    public static void main(String[] args) {
        try {
            Stream<String> lines = Files.lines(Paths.get("app.log"));
            List<String> content = lines.collect(Collectors.toList());
            content.forEach(x -> System.out.println(x));
        } catch (IOException e) {
            System.err.format("IOException: %s%n", e);
Terminal
Line 1
Line 2
Line 3
Line 4
Line 5

2. Files.readAllBytes

In Java 7, we can use Files.readAllBytes or Files.readAllLines to read a file, it will close the resources (opened file) automatically.

FileExample2.java
package com.mkyong;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class FileExample2 {
    public static void main(String[] args) {
        try {
            byte[] bytes = Files.readAllBytes(Paths.get("app.log"));
            String content = new String(bytes);
            System.out.println(content);
        } catch (IOException e) {
            System.err.format("IOException: %s%n", e);

Output

Terminal
Line 1
Line 2
Line 3
Line 4
Line 5

3. BufferedReader

3.1 A classic BufferedReader with try-with-resources to auto close the resources.

FileExample3.java
package com.mkyong;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileExample3 {
    public static void main(String[] args) {
        try (FileReader reader = new FileReader("app.log");
             BufferedReader br = new BufferedReader(reader)) {
            // read line by line
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
        } catch (IOException e) {
            System.err.format("IOException: %s%n", e);

3.2 In the old days, we have to close everything manually.

FileExample3.java
package com.mkyong.calculator;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileExample3 {
    public static void main(String[] args) {
        BufferedReader br = null;
        FileReader fr = null;
        try {
            fr = new FileReader("app.log");
            br = new BufferedReader(fr);
            // read line by line
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
        } catch (IOException e) {
            System.err.format("IOException: %s%n", e);
        } finally {
            try {
                if (br != null)
                    br.close();
                if (fr != null)
                    fr.close();
            } catch (IOException ex) {
                System.err.format("IOException: %s%n", ex);

4. Scanner

Let end this article with the classic Scanner example.

FileExample4.java
package com.mkyong;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class FileExample4 {
    public static void main(String[] args) {
        try (FileReader fr = new FileReader("app.log");
             Scanner scanner = new Scanner(fr)) {
            StringBuilder sb = new StringBuilder();
            while (scanner.hasNext()) {
                sb.append(scanner.nextLine()).append("\n");
            System.out.println(sb.toString());
        } catch (IOException e) {
            System.err.format("IOException: %s%n", e);

上一篇: Java How to send Email
下一篇: Java How to create and write to a file
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号