Java中如何将文件读入列表呢?

乔欣 Java经验 发布时间:2023-02-02 11:39:45 阅读数:10027 1
下文笔者讲述将文件读入列表的方法分享,如下所示

文件读入列表

实现思路:
    jdk8中使用Files.lines读取相应的内容
	jdk7中使用FileReader读取相应的内容

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

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();
		}
	}
例:文件读入到List中的示例
package com.java265.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:\\testInfo.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;
    }
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202302/16753096035627.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者