复制文件 通过该方式复制文件文件越大速度越是明显 @param file 需要处理的文件 @param targetFile 目标文件 @return 是否成功
(File file, File targetFile)
| 387 | * @return 是否成功 |
| 388 | */ |
| 389 | public static boolean copyFile(File file, File targetFile) throws IOException { |
| 390 | logger.debug("copy file resource:{} ,target:{}", file.getAbsolutePath(), targetFile.getAbsolutePath()); |
| 391 | int BUFFER_SIZE = 1024 * 1024; |
| 392 | if (!targetFile.getParentFile().exists()) { |
| 393 | targetFile.getParentFile().mkdirs(); |
| 394 | } |
| 395 | targetFile.createNewFile(); |
| 396 | try ( |
| 397 | FileInputStream fin = new FileInputStream(file); |
| 398 | FileOutputStream fout = new FileOutputStream(targetFile) |
| 399 | ) { |
| 400 | FileChannel in = fin.getChannel(); |
| 401 | FileChannel out = fout.getChannel(); |
| 402 | ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); |
| 403 | while (in.read(buffer) != -1) { |
| 404 | buffer.flip(); |
| 405 | out.write(buffer); |
| 406 | buffer.clear(); |
| 407 | } |
| 408 | return true; |
| 409 | } catch (IOException e) { |
| 410 | throw e; |
| 411 | } |
| 412 | } |
| 413 | |
| 414 | |
| 415 | /////////////////////////////////////////////////////////////////////// |