EBookMgr 文件拷贝(你知道缓冲多大时拷贝文件的速度最快吗?)

在导入电子书的过程中需要将电子书从原始位置拷贝到书库,这个过程需要设计一个拷贝方法,参看以下代码:

private static void copyFile(String fromFile, String toFolder) throws IOException { InputStream in = null; OutputStream out = null; try { File targetFolder = new File(toFolder); if (!targetFolder.exists()) { targetFolder.mkdirs(); } File from = new File(fromFile); File to = new File(toFolder, from.getName()); in = new FileInputStream(from); out = new FileOutputStream(to); byte[] buf = new byte[Configuration.BUFFER_SIZE]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } finally { EBookMgrUtil.safelyClose(in); EBookMgrUtil.safelyClose(out); } }

这样实现基于以下考虑:

1. try-catch-finally原则

所有重要的资源都在finally中关闭

2. 拷贝一个文件到一个目录,使用相同的文件

3. 减少无用代码,流在关闭的时候都会抛出IOException,但是此时处理时无用的,所以使用了safelyClose重载方法,参看以下代码:

public static void safelyClose(InputStream is) { if(is != null) { try { is.close(); } catch (IOException ex) { ex.printStackTrace(); } } } public static void safelyClose(OutputStream os) { if(os != null) { try { os.flush(); os.close(); } catch (IOException ex) { ex.printStackTrace(); } } }

4. 为了统一处理异常,这个方法没有使用catch块

所有内容如上,代码本身应该没有在优化的必要,影响性能的最重要的地方是:

byte[] buf = new byte[Configuration.BUFFER_SIZE];

也就是说文件拷贝时使用的缓冲区的大小,参看以下文章:

http://www.xiguaforever.net/confluence/display/JPT/Java+File+IO+Analysis#JavaFileIOAnalysis-Conclusion

我们可以得知在缓冲区为64k时拷贝电子书(1M~5M大小)性能相对最好。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值