Java –如何将文件读入列表?

在Java中,几乎没有办法将文件逐行读取到List

1. Java 8流

List<String> result;
	try (Stream<String> lines = Files.lines(Paths.get(fileName))) {
		result = lines.collect(Collectors.toList());
	}

2. Java 7

Files.readAllLines(new File(fileName).toPath(), Charset.defaultCharset());

3.经典的BufferedReader示例。

List<String> result = new ArrayList<>();
	BufferedReader br = null;

	try {

		br = new BufferedReader(new FileReader(fileName));

		String line;
		while ((line = br.readLine()) != null) {
			result.add(line);
		}

	} catch (IOException e) {
		e.printStackTrace();
	} finally {
		if (br != null) {
			br.close();
		}
	}

1.文件->列表

1.1虚拟文件

d:\\server.log
a
b
c
d
1
2
3

1.2将文件读入List

JavaExample.java
package com.mkyong.example;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class JavaExample {

    public static void main(String[] args) {

        String filename = "d:\\server.log";

        try {
            List list = readByJavaClassic(filename);
            list.forEach(System.out::println);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    private static List readByJava8(String fileName) throws IOException {
        List<String> result;
        try (Stream<String> lines = Files.lines(Paths.get(fileName))) {
            result = lines.collect(Collectors.toList());
        }
        return result;

    }

    private static List readByJava7(String fileName) throws IOException {
        return Files.readAllLines(new File(fileName).toPath(), Charset.defaultCharset());
    }

    private static List readByJavaClassic(String fileName) throws IOException {

        List<String> result = new ArrayList<>();
        BufferedReader br = null;

        try {

            br = new BufferedReader(new FileReader(fileName));

            String line;
            while ((line = br.readLine()) != null) {
                result.add(line);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                br.close();
            }
        }

        return result;
    }

}

输出量

a
b
c
d
1
2
3

参考文献

  1. Java 8 Stream –逐行读取文件

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值