|
66 | 66 | *
|
67 | 67 | * @author Sebastien Deleuze
|
68 | 68 | * @author Rossen Stoyanchev
|
| 69 | + * @author Arjen Poutsma |
69 | 70 | * @since 5.0
|
70 | 71 | * @see <a href="https://github.com/synchronoss/nio-multipart">Synchronoss NIO Multipart</a>
|
71 | 72 | */
|
@@ -301,22 +302,45 @@ public Flux<DataBuffer> getContent() {
|
301 | 302 | }
|
302 | 303 |
|
303 | 304 | @Override
|
304 |
| - public Mono<Void> transferTo(File dest) { |
| 305 | + public Mono<Void> transferTo(File destination) { |
305 | 306 | if (this.storage == null || !getFilename().isPresent()) {
|
306 | 307 | return Mono.error(new IllegalStateException("The part does not represent a file."));
|
307 | 308 | }
|
| 309 | + ReadableByteChannel input = null; |
| 310 | + FileChannel output = null; |
308 | 311 | try {
|
309 |
| - ReadableByteChannel ch = Channels.newChannel(this.storage.getInputStream()); |
310 |
| - long expected = (ch instanceof FileChannel ? ((FileChannel) ch).size() : Long.MAX_VALUE); |
311 |
| - long actual = new FileOutputStream(dest).getChannel().transferFrom(ch, 0, expected); |
312 |
| - if (actual < expected) { |
313 |
| - return Mono.error(new IOException( |
314 |
| - "Could only write " + actual + " out of " + expected + " bytes")); |
| 312 | + input = Channels.newChannel(this.storage.getInputStream()); |
| 313 | + output = new FileOutputStream(destination).getChannel(); |
| 314 | + |
| 315 | + long size = (input instanceof FileChannel ? ((FileChannel) input).size() : Long.MAX_VALUE); |
| 316 | + long totalWritten = 0; |
| 317 | + while (totalWritten < size) { |
| 318 | + long written = output.transferFrom(input, totalWritten, size - totalWritten); |
| 319 | + if (written <= 0) { |
| 320 | + break; |
| 321 | + } |
| 322 | + totalWritten += written; |
315 | 323 | }
|
316 | 324 | }
|
317 | 325 | catch (IOException ex) {
|
318 | 326 | return Mono.error(ex);
|
319 | 327 | }
|
| 328 | + finally { |
| 329 | + if (input != null) { |
| 330 | + try { |
| 331 | + input.close(); |
| 332 | + } |
| 333 | + catch (IOException ignored) { |
| 334 | + } |
| 335 | + } |
| 336 | + if (output != null) { |
| 337 | + try { |
| 338 | + output.close(); |
| 339 | + } |
| 340 | + catch (IOException ignored) { |
| 341 | + } |
| 342 | + } |
| 343 | + } |
320 | 344 | return Mono.empty();
|
321 | 345 | }
|
322 | 346 | }
|
|
0 commit comments