文件传输和时间格式

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

    }

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值