在导入电子书的过程中需要将电子书从原始位置拷贝到书库,这个过程需要设计一个拷贝方法,参看以下代码:
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];
也就是说文件拷贝时使用的缓冲区的大小,参看以下文章:
我们可以得知在缓冲区为64k时拷贝电子书(1M~5M大小)性能相对最好。