博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java读取txt文件
阅读量:6937 次
发布时间:2019-06-27

本文共 1529 字,大约阅读时间需要 5 分钟。

一、读取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();        }    }}

二、拓展...

场景 : 正则匹配

转载于:https://www.cnblogs.com/chenmo-xpw/p/5578614.html

你可能感兴趣的文章
MS MVC框架漩涡中的MonoRail未来
查看>>
Linux 5.4 RHCE Sendmail 学习笔记基础配置
查看>>
Swig之cpp完整python扩展疑难对策
查看>>
LFS资料和SSH远程登录全过程
查看>>
原型模式(Prototype)解析例子
查看>>
Linux snmp服务开启远程监控
查看>>
Windows Azure恢复服务功能介绍
查看>>
Oracle exp query条件检索在WINDOWS和LINUX下的命令区别
查看>>
虚幻引擎学习之路:粒子系统篇(二)
查看>>
9月24日百度校园招聘运维职位笔试地点
查看>>
Centos7无法使用ssh登陆及解决方案
查看>>
Oracle进程连接数过多时的Statspack分析报告
查看>>
Docker 教程
查看>>
技术分享连载(四十七)
查看>>
故障和心态
查看>>
关于exchange数据库无法装载问题分析处理
查看>>
Memcache 应用详解
查看>>
HTTP管线化(HTTP pipelining)
查看>>
debian6修改输入法
查看>>
企业级硬盘分类
查看>>