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

    }
}

二、拓展...

场景 : 正则匹配

posted @ 2016-06-12 19:52  坚守一辈子的幸福  阅读(1273)  评论(0编辑  收藏  举报