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

    二、拓展...

    场景 : 正则匹配

  • 相关阅读:
    母函数详解
    java中为什么要实现序列化,什么时候实现序列化?
    cocos2dx&cocosbuilder折腾记
    Unity3D系列教程–使用免费工具在Unity3D中开发2D游戏 第二节(下)
    分頁查詢
    獲取CPU,硬盤序列號
    spcomm
    dbgrideh的導入和導出
    程序窗体及控件自适应分辨率
    組合的藝術
  • 原文地址:https://www.cnblogs.com/chenmo-xpw/p/5578614.html
Copyright © 2011-2022 走看看