java读取txt文件行的两种方式对比

2020-12-22 08:27

阅读:611

标签:对比   fileinput   inpu   cep   rac   nes   lines   catch   bsp   

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * 读取txt文件的行
 *
 */
public class FileUtil {
    /**
     * java.nio.file.Files方式
     * @param filePath
     * @return
     */
    public static List parseFileContext(String filePath) {
        System.out.println("filePath="+filePath);
        List dataArray = null;
        try {
            dataArray = Files.readAllLines(Paths.get(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return dataArray;
    }
    
    /**
     * 流方式
     * @param filePath
     * @return
     */
    public static List oldParseFileContext(String filePath) {
        System.out.println("filePath="+filePath);
        
        List dataArray = new ArrayList();
        
        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader br = null; // 用于包装InputStreamReader,提高处理性能。因为BufferedReader有缓冲的,而InputStreamReader没有。
        try {
            String str = "";
            fis = new FileInputStream(filePath);// FileInputStream
    
            isr = new InputStreamReader(fis);
            br = new BufferedReader(isr);
            while ((str = br.readLine()) != null) {
                dataArray.add(str);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                br.close();
                isr.close();
                fis.close();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return dataArray;
    }
    

    public static void main(String[] args) {
        String path = "E:\\test.txt";
//        List lst = parseFileContext(path);
        List lst = oldParseFileContext(path);
        for (String string : lst) {
            System.out.println("string="+string);
        }
    }

}

 

java读取txt文件行的两种方式对比

标签:对比   fileinput   inpu   cep   rac   nes   lines   catch   bsp   

原文地址:https://www.cnblogs.com/oktokeep/p/13217314.html


评论


亲,登录后才可以留言!