Java –如何读取文件

在Java中,几乎没有读取文件的方法。

1. Java 8 – Files.lines ,它将返回一个Stream

//@Since 1.8

	Stream<String> lines = Files.lines(Paths.get("app.log"));

	List<String> content = lines.collect(Collectors.toList());

2. Java 7 – Files.readAllBytesFiles.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.和这个经典的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

在Java 8中,我们可以使用Files.lines将文件读入Stream ,它将自动关闭资源(打开的文件)。

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

在Java 7中,我们可以使用Files.readAllBytesFiles.readAllLines读取文件,它将自动关闭资源(打开的文件)。

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);
        }
    }

}

输出量

Terminal
Line 1
Line 2
Line 3
Line 4
Line 5

3. BufferedReader

3.1一个经典的BufferedReader带有try-with-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在过去,我们必须手动关闭所有内容。

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示例结束本文。

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);
        }

    }

}

参考文献

翻译自: https://mkyong.com/java/java-how-to-read-a-file/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值