文件传输和时间格式
?1.??注意一点是 month 是从0开始,所以要+1
?
/** * 获取当前时间:xxxx年xx月xx日xx小时xx分xx秒 * * @return String */ private String getCurrentDate() { Calendar ca = Calendar.getInstance(); int year = ca.get(Calendar.YEAR);//年 int month = ca.get(Calendar.MONTH) + 1;//月 int day = ca.get(Calendar.DATE);//日 int minute = ca.get(Calendar.MINUTE);//分 int hour = ca.get(Calendar.HOUR_OF_DAY);//小时(24小时制) int second = ca.get(Calendar.SECOND);//秒 return year + "年" + month + "月" + day + "日" + hour + "时" + minute + "分" + second + "秒"; }?
2. 文件传输:注意关闭流的时候一定要在finally中,否则可能由于异常情况,导致流不能正确关闭。
两个流关闭的时候不能在finally中直接顺序close.因为可能在关闭其中一个流异常,导致另一个流不能正确关闭。
还有就是流关闭后,并不为null,判断是否关闭用getFD().valid()方法。
?
private static long dataTransfer(String sourceFilePath, String targetFilePath) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { File sourceFile = new File(sourceFilePath); File targetFile = new File(targetFilePath); long time = new Date().getTime(); in = new FileInputStream(sourceFile); out = new FileOutputStream(targetFile); byte[] buffer = new byte[Constants.BYTE_SIZE]; try { while (true) { int ins = in.read(buffer); if (ins == -1) { in.close(); out.flush(); out.close(); return (new Date().getTime() - time) / 1000; } else { out.write(buffer, 0, ins); } } } catch (IOException e) { logger.error("数据传输异常", e); throw e; } finally { try { if (in != null && in.getFD().valid()) { in.close(); } } catch (IOException e) { logger.error("数据传输异常", e); throw e; } } } catch (IOException e) { logger.error("数据传输异常", e); throw e; } finally { try { if (out != null && out.getFD().valid()) { out.close(); } } catch (IOException e) { logger.error("数据传输异常", e); throw e; } } }?
?
?