Java How to read a file into a list?

摘要: In Java, there are few ways to read a file line by line into a List

In Java, there are few ways to read a file line by line into a List

1. Java 8 stream

	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. Classic BufferedReader example.

	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. File -> List

1.1 A dummy file

d:\\server.log

1.2 Read file into a 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;

Output


References

  1. Java 8 Stream – Read a file line by line

上一篇: Java Files.walk examples
下一篇: Python How to read a file into a list?
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

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

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

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