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 public class FileLocation
31 implements Location
32 {
33
34 private File file;
35 private FileChannel channel;
36 private final String specification;
37 private FileInputStream stream;
38
39 public FileLocation( File file, String specification )
40 {
41 this.file = file;
42 this.specification = specification;
43 }
44
45 protected FileLocation( String specification )
46 {
47 this.specification = specification;
48 }
49
50 public void close()
51 {
52 if ( ( channel != null ) && channel.isOpen() )
53 {
54 try
55 {
56 channel.close();
57 }
58 catch ( IOException e )
59 {
60
61 }
62 }
63
64 if ( stream != null )
65 {
66 try
67 {
68 stream.close();
69 }
70 catch( IOException e )
71 {
72
73 }
74 }
75 }
76
77 public File getFile()
78 throws IOException
79 {
80 initFile();
81
82 return unsafeGetFile();
83 }
84
85 protected File unsafeGetFile()
86 {
87 return file;
88 }
89
90 protected void initFile()
91 throws IOException
92 {
93
94 if ( file == null )
95 {
96 file = new File( specification );
97 }
98 }
99
100 protected void setFile( File file )
101 {
102 if ( channel != null )
103 {
104 throw new IllegalStateException( "Location is already open; cannot setFile(..)." );
105 }
106
107 this.file = file;
108 }
109
110 public String getSpecification()
111 {
112 return specification;
113 }
114
115 public void open()
116 throws IOException
117 {
118 if ( stream == null )
119 {
120 initFile();
121
122 stream = new FileInputStream( file );
123 channel = stream.getChannel();
124 }
125 }
126
127 public int read( ByteBuffer buffer )
128 throws IOException
129 {
130 open();
131 return channel.read( buffer );
132 }
133
134 public int read( byte[] buffer )
135 throws IOException
136 {
137 open();
138 return channel.read( ByteBuffer.wrap( buffer ) );
139 }
140
141 public InputStream getInputStream()
142 throws IOException
143 {
144 open();
145 return stream;
146 }
147
148 }