java 读取文本流的2种方式

例子:

public class test2 {
    
    public static String filePath="/Users/电脑/Desktop/kk.txt";

    //第1种:普通方式:
    public static void redFile() throws Exception{

                                //缓冲流               //字符转换流           //文件字节输入流
      try(BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(filePath)))){
           String data= null;
           while (null != (data=br.readLine())){//遍历每一行打印
               System.out.println("普通获取:"+data);
           }
      }catch (Exception e) {
          e.printStackTrace();
      }
    }

    //第2种:jdk8 Stream流式读取方式:

    public static void streamRedFile() throws Exception{
        try(Stream<String> stream= Files.lines(Paths.get(filePath), Charset.defaultCharset())){
            stream.forEach(System.out::println);//函数式的写法
        }
    }


    public static void main(String args[]) {

        //读取文本的2种方式

        //第1种
        try {
            redFile();
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("-------------------------------------");

        //第2种
        try {
            streamRedFile();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }
}

打印:


普通获取:Asdsadas
普通获取:1111
普通获取:22222
普通获取:2333
普通获取:434343
-------------------------------------
Asdsadas
1111
22222
2333
434343

第三种:

public static ArrayList<String> readFromTextFile(String pathname) throws IOException {
        ArrayList<String> strArray = new ArrayList<String>();
        File filename = new File(pathname);
        InputStreamReader reader = new InputStreamReader(new FileInputStream(filename));
        BufferedReader br = new BufferedReader(reader);
        String line = "";
        line = br.readLine();
        while(line != null) {
            strArray.add(line);
            line = br.readLine();
        }
        return strArray;
    }
    public static void main(String args[]) {

        try {
            ArrayList<String> list=readFromTextFile(filePath);
            for (int i = 0; i < list.size(); i++) {
                System.out.println("========="+list.get(i).toString());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

结果:

=========#in the frame Video positions
=========label_mask=65
=========#video position
=========#layout
=========label_number=72
=========# possible to define

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我先来一碗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值