16
16
import static org .asynchttpclient .util .MiscUtils .closeSilently ;
17
17
import io .netty .buffer .ByteBuf ;
18
18
19
- import java .io .FileInputStream ;
20
- import java .io .FileNotFoundException ;
21
- import java .io .IOException ;
19
+ import java .io .*;
22
20
import java .nio .channels .FileChannel ;
23
21
import java .nio .channels .WritableByteChannel ;
24
22
27
25
28
26
public class FileMultipartPart extends FileLikeMultipartPart <FilePart > {
29
27
30
- private final FileChannel channel ;
28
+ private FileChannel channel ;
31
29
private final long length ;
32
30
private long position = 0L ;
33
31
34
- @ SuppressWarnings ("resource" )
32
+ private FileChannel getChannel () throws IOException {
33
+ if (channel == null ) {
34
+ channel = new RandomAccessFile (part .getFile (), "r" ).getChannel ();
35
+ }
36
+ return channel ;
37
+ }
38
+
35
39
public FileMultipartPart (FilePart part , byte [] boundary ) {
36
40
super (part , boundary );
37
- try {
38
- channel = new FileInputStream (part .getFile ()).getChannel ();
39
- } catch (FileNotFoundException e ) {
40
- throw new IllegalArgumentException ("File part doesn't exist: " + part .getFile ().getAbsolutePath (), e );
41
+ File file = part .getFile ();
42
+ if (!file .exists ()) {
43
+ throw new IllegalArgumentException ("File part doesn't exist: " + file .getAbsolutePath ());
44
+ } else if (!file .canRead ()) {
45
+ throw new IllegalArgumentException ("File part can't be read: " + file .getAbsolutePath ());
41
46
}
42
- length = part . getFile () .length ();
47
+ length = file .length ();
43
48
}
44
49
45
50
@ Override
@@ -50,7 +55,7 @@ protected long getContentLength() {
50
55
@ Override
51
56
protected long transferContentTo (ByteBuf target ) throws IOException {
52
57
// can return -1 if file is empty or FileChannel was closed
53
- int transferred = target .writeBytes (channel , target .writableBytes ());
58
+ int transferred = target .writeBytes (getChannel () , target .writableBytes ());
54
59
if (transferred > 0 ) {
55
60
position += transferred ;
56
61
}
@@ -66,8 +71,9 @@ protected long transferContentTo(ByteBuf target) throws IOException {
66
71
@ Override
67
72
protected long transferContentTo (WritableByteChannel target ) throws IOException {
68
73
// WARN: don't use channel.position(), it's always 0 here
69
- // from FileChannel javadoc: "This method does not modify this channel's position."
70
- long transferred = channel .transferTo (position , BodyChunkedInput .DEFAULT_CHUNK_SIZE , target );
74
+ // from FileChannel javadoc: "This method does not modify this channel's
75
+ // position."
76
+ long transferred = getChannel ().transferTo (position , BodyChunkedInput .DEFAULT_CHUNK_SIZE , target );
71
77
if (transferred > 0 ) {
72
78
position += transferred ;
73
79
}
0 commit comments