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

 

你可能感兴趣的:(JAVA基础)