拷贝文件的函数,之前的写法:
039 // 复制文件 |
045 destOut = new FileOutputStream(to);
|
|
046 byte[] buff = new byte[1024];
|
047 int len; |
048 while (-1 != (len = srcIn.read(buff))) {
|
049 destOut.write(buff, 0, len); |
056 if (null != srcIn)
|
|
057 srcIn.close();
|
|
058 } catch (IOException e) {
|
|
059 throw e;
|
060 } |
一直报错,原因是srcIn关闭异常之后,如何destOut可能就关闭失败。
// 复制文件 public static void copyfile(File from, String to) throws Exception { FileInputStream srcIn = null; FileOutputStream destOut = null; try { srcIn = new FileInputStream(from); destOut = new FileOutputStream(to); byte[] buff = new byte[1024]; int len; while (-1 != (len = srcIn.read(buff))) { destOut.write(buff, 0, len); } destOut.close(); } finally { try { if (null != destOut) { destOut.close(); } }finally { if (null != srcIn) { srcIn.close(); } } } }
本文介绍了一种改进的文件复制方法,解决了原有方法中输入输出流关闭顺序导致的问题。通过调整关闭顺序并在finally块中处理输出流关闭,确保了文件复制过程的稳定性和资源的有效释放。
1万+

被折叠的 条评论
为什么被折叠?



