zoukankan      html  css  js  c++  java
  • java读取txt文件

    一、读取txt文件。

    1、步骤 : 

    ①、创建文件句柄

    File file = new File(filePath);

    ②、将文件内容读取到内存中

    new FileInputStream(file)

    ③、封装数据 InputStreamReader

    InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding)

    ④、读取数据

    BufferedReader bufferedReader = new BufferedReader(read);

      每行数据

    bufferedReader.readLine()

    2、场景 : txt文件内容 :

    123

    456

    ...

    读取每行内容, 并将每行内容用 , 拼接成  123,456

    public class ReadTxt {
        
        public static void main(String[] args) {
            String filePath = "/Users/xupengwei/Downloads/test.txt";
            readTxtFile(filePath );
        }
    
        public static void readTxtFile(String filePath) {
            try {
                String encoding = "GBK";
                File file = new File(filePath);
                if (file.isFile() && file.exists()) { // 判断文件是否存在
                    InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);// 考虑到编码格式
                    BufferedReader bufferedReader = new BufferedReader(read);
                    String lineTxt = null;
                    StringBuffer sb = new StringBuffer();
                    while ((lineTxt = bufferedReader.readLine()) != null) {
                        sb.append(lineTxt);
                        sb.append(",");
                    }
                    System.out.println(sb.toString());
                    read.close();
                } else {
                    System.out.println("找不到指定的文件");
                }
            } catch (Exception e) {
                System.out.println("读取文件内容出错");
                e.printStackTrace();
            }
    
        }
    }

    二、拓展...

    场景 : 正则匹配

  • 相关阅读:
    ASCII码详解
    C#中判断上传类型为Excel,03和07版的链接字符串
    文本搜索工具的制作过程之搜索
    文本搜索工具之显示
    用C#实现十六进制字符串转换为ASCII
    7个秘诀 工作效率和薪水都翻倍
    C#委托
    VB的写法,关于版本写入注册表
    k8s 集群灾难恢复 k8s
    k8s 接合阿里云负载均衡 k8s
  • 原文地址:https://www.cnblogs.com/chenmo-xpw/p/5578614.html
Copyright © 2011-2022 走看看