首页 > 编程语言 > 详细

java读取txt文件

时间:2016-06-12 20:21:43      阅读:233      评论:0      收藏:0      [点我收藏+]

一、读取txt文件。

场景 : 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读取txt文件

原文:http://www.cnblogs.com/chenmo-xpw/p/5578614.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!