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