java 判断文件是否存在 按行读取 自己的修改版 测试通过

首先,这样的代码这十多年写过不少次了,但好像每次写的都不太一样。以前一直都流行按字节读取。每次都从网上找来差不多的,然后用。但网上有不少按行读取再写出的代码,但我在使用之后发现读取时总会有些莫名其妙的问题,比如少读,重读。有不少网上代码直接使用了while ((tempString = reader.readLine())!= null) ,但这样会有少读的情况发生。比如第一行。我不知道大家会不会有这样的情况。我测了N次都会这样。

 

于是自己改善了一下。另外,readline的源码也看了一下,其实就是判断/r和/n。但在windows中和linux中,这两个的函意还是不一样的。linux下没有细测。

 

SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");// 设置日期格式
		long begin0 = System.currentTimeMillis();
		filePath = "c:\\smslog_" + df.format(new Date());
		File file = new File(filePath);
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		try {
			StringBuffer sb= new StringBuffer("");
			BufferedReader  reader = new BufferedReader(new FileReader(file));
			String tempString = reader.readLine();
			sb.append(tempString + "\r\n");
			// 一次读入一行,直到读入null为文件结束
			while ((tempString = reader.readLine())!= null) {
				sb.append(tempString+"\r\n");
			}
			reader.close();

			df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
			sb.append("平台信息回复:" + info + "-------操作时间:" + df.format(new Date()));
			BufferedWriter bWriterout = new BufferedWriter(new FileWriter(filePath));			
			bWriterout.write(sb.toString());
			bWriterout.newLine(); // 注意\n不一定在各种计算机上都能产生换行的效果
			bWriterout.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值