1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.plugins.assembly.io;
20
21 import java.io.File;
22 import java.io.FileInputStream;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.nio.ByteBuffer;
26 import java.nio.channels.FileChannel;
27
28
29
30
31
32 class FileLocation implements Location {
33
34 private File file;
35 private FileChannel channel;
36 private final String specification;
37 private FileInputStream stream;
38
39
40
41
42
43 FileLocation(File file, String specification) {
44 this.file = file;
45 this.specification = specification;
46 }
47
48
49
50
51 FileLocation(String specification) {
52 this.specification = specification;
53 }
54
55 @Override
56 public void close() {
57 if ((channel != null) && channel.isOpen()) {
58 try {
59 channel.close();
60 } catch (IOException e) {
61
62 }
63 }
64
65 if (stream != null) {
66 try {
67 stream.close();
68 } catch (IOException e) {
69
70 }
71 }
72 }
73
74 @Override
75 public File getFile() throws IOException {
76 initFile();
77
78 return unsafeGetFile();
79 }
80
81
82
83
84 File unsafeGetFile() {
85 return file;
86 }
87
88
89
90
91
92 protected void initFile() throws IOException {
93 if (file == null) {
94 file = new File(specification);
95 }
96 }
97
98
99
100
101 protected void setFile(File file) {
102 if (channel != null) {
103 throw new IllegalStateException("Location is already open; cannot setFile(..).");
104 }
105
106 this.file = file;
107 }
108
109 @Override
110 public String getSpecification() {
111 return specification;
112 }
113
114 @Override
115 public void open() throws IOException {
116 if (stream == null) {
117 initFile();
118
119 stream = new FileInputStream(file);
120 channel = stream.getChannel();
121 }
122 }
123
124 @Override
125 public int read(ByteBuffer buffer) throws IOException {
126 open();
127 return channel.read(buffer);
128 }
129
130 @Override
131 public int read(byte[] buffer) throws IOException {
132 open();
133 return channel.read(ByteBuffer.wrap(buffer));
134 }
135
136 @Override
137 public InputStream getInputStream() throws IOException {
138 open();
139 return stream;
140 }
141 }