java处理TXT文件

有时候需要对一些数据进行批量分析和操作(比如数据库查询出来的字段信息) ,这时我们可以将其放在txt或者excel文件中,然后对txt进行读取并处理逻辑。txt文件内容按如下显示:

oid sid

1 2

1 3

下面给出操作txt文件的工具代码:

 

public class ReadTxtUtils {

 

private File filename ;

private InputStreamReader reader;

private BufferedReader br ;

public ReadTxtUtils(String filepath) {

try {

File file = new File(filepath);

reader = new InputStreamReader(new FileInputStream(file), "gbk");

br = new BufferedReader(reader);

} catch (Exception e) {

}

}

 

public void readTxtContent() throws Exception{

long starttime=System.currentTimeMillis();

String line = "";

line = br.readLine();

int i = 0;

int errorCount=0;

while (line != null) {

if(i > 0 && !StringUtils.isEmpty(line)){

line = br.readLine(); //第一行数据

String[] lines = null;//

if(line!=null){

lines=line.split(" ");

}else{

continue;

}

try {

String oid = lines[0].trim();

String sid =lines[1].trim();

String url="http://testapi.crius.cn/test_web/updateUserId";

//请求参数

HashMap<String, Object> requestMap = new HashMap<String, Object>();

requestMap.put("oid ",oid );

requestMap.put("sid",sid);

HttpUtil.doPost(url,requestMap,null);//这里是http请求调用其他服务处理数据

} catch (Exception e) {

errorCount++;

System.out.println("oid==="+lines[0].trim());

}

}

i = i + 1;

}

System.out.println("错误数据记录数"+errorCount);

long endtime=System.currentTimeMillis();

System.out.println("总用时(min):"+(endtime-starttime)/1000/60);

System.out.println("总张数(min):"+i);

}

public static boolean createDir(String destDirName) {

File dir = new File(destDirName);

if (dir.exists()) {

// System.out.println("创建目录" + destDirName + "失败,目标目录已经存在");

return false;

}

if (!destDirName.endsWith(File.separator)) {

destDirName = destDirName + File.separator;

}

//创建目录

if (dir.mkdirs()) {

System.out.println("创建目录" + destDirName + " 成功!");

return true;

} else {

System.out.println("创建目录" + destDirName + "失败!");

return false;

}

}

public static void main(String[] args) {

try {

String filepath = "C:/Users/crius/Desktop/1.txt";

ReadTxtUtils excelReader = new ReadTxtUtils(filepath);

excelReader.readTxtContent();

}catch (Exception e) {

System.out.println("未找到指定路径的文件!");

e.printStackTrace();

}

}

}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值