001/*
002 * Copyright 2002-2019 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.core.io;
018
019import java.io.File;
020import java.io.FileNotFoundException;
021import java.io.IOException;
022import java.io.InputStream;
023import java.io.OutputStream;
024import java.net.URI;
025import java.net.URL;
026import java.nio.channels.FileChannel;
027import java.nio.channels.ReadableByteChannel;
028import java.nio.channels.WritableByteChannel;
029import java.nio.file.FileSystem;
030import java.nio.file.Files;
031import java.nio.file.NoSuchFileException;
032import java.nio.file.Path;
033import java.nio.file.StandardOpenOption;
034
035import org.springframework.lang.Nullable;
036import org.springframework.util.Assert;
037import org.springframework.util.StringUtils;
038
039/**
040 * {@link Resource} implementation for {@code java.io.File} and
041 * {@code java.nio.file.Path} handles with a file system target.
042 * Supports resolution as a {@code File} and also as a {@code URL}.
043 * Implements the extended {@link WritableResource} interface.
044 *
045 * <p>Note: As of Spring Framework 5.0, this {@link Resource} implementation uses
046 * NIO.2 API for read/write interactions. As of 5.1, it may be constructed with a
047 * {@link java.nio.file.Path} handle in which case it will perform all file system
048 * interactions via NIO.2, only resorting to {@link File} on {@link #getFile()}.
049 *
050 * @author Juergen Hoeller
051 * @since 28.12.2003
052 * @see #FileSystemResource(String)
053 * @see #FileSystemResource(File)
054 * @see #FileSystemResource(Path)
055 * @see java.io.File
056 * @see java.nio.file.Files
057 */
058public class FileSystemResource extends AbstractResource implements WritableResource {
059
060        private final String path;
061
062        @Nullable
063        private final File file;
064
065        private final Path filePath;
066
067
068        /**
069         * Create a new {@code FileSystemResource} from a file path.
070         * <p>Note: When building relative resources via {@link #createRelative},
071         * it makes a difference whether the specified resource base path here
072         * ends with a slash or not. In the case of "C:/dir1/", relative paths
073         * will be built underneath that root: e.g. relative path "dir2" ->
074         * "C:/dir1/dir2". In the case of "C:/dir1", relative paths will apply
075         * at the same directory level: relative path "dir2" -> "C:/dir2".
076         * @param path a file path
077         * @see #FileSystemResource(Path)
078         */
079        public FileSystemResource(String path) {
080                Assert.notNull(path, "Path must not be null");
081                this.path = StringUtils.cleanPath(path);
082                this.file = new File(path);
083                this.filePath = this.file.toPath();
084        }
085
086        /**
087         * Create a new {@code FileSystemResource} from a {@link File} handle.
088         * <p>Note: When building relative resources via {@link #createRelative},
089         * the relative path will apply <i>at the same directory level</i>:
090         * e.g. new File("C:/dir1"), relative path "dir2" -> "C:/dir2"!
091         * If you prefer to have relative paths built underneath the given root directory,
092         * use the {@link #FileSystemResource(String) constructor with a file path}
093         * to append a trailing slash to the root path: "C:/dir1/", which indicates
094         * this directory as root for all relative paths.
095         * @param file a File handle
096         * @see #FileSystemResource(Path)
097         * @see #getFile()
098         */
099        public FileSystemResource(File file) {
100                Assert.notNull(file, "File must not be null");
101                this.path = StringUtils.cleanPath(file.getPath());
102                this.file = file;
103                this.filePath = file.toPath();
104        }
105
106        /**
107         * Create a new {@code FileSystemResource} from a {@link Path} handle,
108         * performing all file system interactions via NIO.2 instead of {@link File}.
109         * <p>In contrast to {@link PathResource}, this variant strictly follows the
110         * general {@link FileSystemResource} conventions, in particular in terms of
111         * path cleaning and {@link #createRelative(String)} handling.
112         * <p>Note: When building relative resources via {@link #createRelative},
113         * the relative path will apply <i>at the same directory level</i>:
114         * e.g. Paths.get("C:/dir1"), relative path "dir2" -> "C:/dir2"!
115         * If you prefer to have relative paths built underneath the given root directory,
116         * use the {@link #FileSystemResource(String) constructor with a file path}
117         * to append a trailing slash to the root path: "C:/dir1/", which indicates
118         * this directory as root for all relative paths. Alternatively, consider
119         * using {@link PathResource#PathResource(Path)} for {@code java.nio.path.Path}
120         * resolution in {@code createRelative}, always nesting relative paths.
121         * @param filePath a Path handle to a file
122         * @since 5.1
123         * @see #FileSystemResource(File)
124         */
125        public FileSystemResource(Path filePath) {
126                Assert.notNull(filePath, "Path must not be null");
127                this.path = StringUtils.cleanPath(filePath.toString());
128                this.file = null;
129                this.filePath = filePath;
130        }
131
132        /**
133         * Create a new {@code FileSystemResource} from a {@link FileSystem} handle,
134         * locating the specified path.
135         * <p>This is an alternative to {@link #FileSystemResource(String)},
136         * performing all file system interactions via NIO.2 instead of {@link File}.
137         * @param fileSystem the FileSystem to locate the path within
138         * @param path a file path
139         * @since 5.1.1
140         * @see #FileSystemResource(File)
141         */
142        public FileSystemResource(FileSystem fileSystem, String path) {
143                Assert.notNull(fileSystem, "FileSystem must not be null");
144                Assert.notNull(path, "Path must not be null");
145                this.path = StringUtils.cleanPath(path);
146                this.file = null;
147                this.filePath = fileSystem.getPath(this.path).normalize();
148        }
149
150
151        /**
152         * Return the file path for this resource.
153         */
154        public final String getPath() {
155                return this.path;
156        }
157
158        /**
159         * This implementation returns whether the underlying file exists.
160         * @see java.io.File#exists()
161         */
162        @Override
163        public boolean exists() {
164                return (this.file != null ? this.file.exists() : Files.exists(this.filePath));
165        }
166
167        /**
168         * This implementation checks whether the underlying file is marked as readable
169         * (and corresponds to an actual file with content, not to a directory).
170         * @see java.io.File#canRead()
171         * @see java.io.File#isDirectory()
172         */
173        @Override
174        public boolean isReadable() {
175                return (this.file != null ? this.file.canRead() && !this.file.isDirectory() :
176                                Files.isReadable(this.filePath) && !Files.isDirectory(this.filePath));
177        }
178
179        /**
180         * This implementation opens a NIO file stream for the underlying file.
181         * @see java.io.FileInputStream
182         */
183        @Override
184        public InputStream getInputStream() throws IOException {
185                try {
186                        return Files.newInputStream(this.filePath);
187                }
188                catch (NoSuchFileException ex) {
189                        throw new FileNotFoundException(ex.getMessage());
190                }
191        }
192
193        /**
194         * This implementation checks whether the underlying file is marked as writable
195         * (and corresponds to an actual file with content, not to a directory).
196         * @see java.io.File#canWrite()
197         * @see java.io.File#isDirectory()
198         */
199        @Override
200        public boolean isWritable() {
201                return (this.file != null ? this.file.canWrite() && !this.file.isDirectory() :
202                                Files.isWritable(this.filePath) && !Files.isDirectory(this.filePath));
203        }
204
205        /**
206         * This implementation opens a FileOutputStream for the underlying file.
207         * @see java.io.FileOutputStream
208         */
209        @Override
210        public OutputStream getOutputStream() throws IOException {
211                return Files.newOutputStream(this.filePath);
212        }
213
214        /**
215         * This implementation returns a URL for the underlying file.
216         * @see java.io.File#toURI()
217         */
218        @Override
219        public URL getURL() throws IOException {
220                return (this.file != null ? this.file.toURI().toURL() : this.filePath.toUri().toURL());
221        }
222
223        /**
224         * This implementation returns a URI for the underlying file.
225         * @see java.io.File#toURI()
226         */
227        @Override
228        public URI getURI() throws IOException {
229                return (this.file != null ? this.file.toURI() : this.filePath.toUri());
230        }
231
232        /**
233         * This implementation always indicates a file.
234         */
235        @Override
236        public boolean isFile() {
237                return true;
238        }
239
240        /**
241         * This implementation returns the underlying File reference.
242         */
243        @Override
244        public File getFile() {
245                return (this.file != null ? this.file : this.filePath.toFile());
246        }
247
248        /**
249         * This implementation opens a FileChannel for the underlying file.
250         * @see java.nio.channels.FileChannel
251         */
252        @Override
253        public ReadableByteChannel readableChannel() throws IOException {
254                try {
255                        return FileChannel.open(this.filePath, StandardOpenOption.READ);
256                }
257                catch (NoSuchFileException ex) {
258                        throw new FileNotFoundException(ex.getMessage());
259                }
260        }
261
262        /**
263         * This implementation opens a FileChannel for the underlying file.
264         * @see java.nio.channels.FileChannel
265         */
266        @Override
267        public WritableByteChannel writableChannel() throws IOException {
268                return FileChannel.open(this.filePath, StandardOpenOption.WRITE);
269        }
270
271        /**
272         * This implementation returns the underlying File/Path length.
273         */
274        @Override
275        public long contentLength() throws IOException {
276                if (this.file != null) {
277                        long length = this.file.length();
278                        if (length == 0L && !this.file.exists()) {
279                                throw new FileNotFoundException(getDescription() +
280                                                " cannot be resolved in the file system for checking its content length");
281                        }
282                        return length;
283                }
284                else {
285                        try {
286                                return Files.size(this.filePath);
287                        }
288                        catch (NoSuchFileException ex) {
289                                throw new FileNotFoundException(ex.getMessage());
290                        }
291                }
292        }
293
294        /**
295         * This implementation returns the underlying File/Path last-modified time.
296         */
297        @Override
298        public long lastModified() throws IOException {
299                if (this.file != null) {
300                        return super.lastModified();
301                }
302                else {
303                        try {
304                                return Files.getLastModifiedTime(this.filePath).toMillis();
305                        }
306                        catch (NoSuchFileException ex) {
307                                throw new FileNotFoundException(ex.getMessage());
308                        }
309                }
310        }
311
312        /**
313         * This implementation creates a FileSystemResource, applying the given path
314         * relative to the path of the underlying file of this resource descriptor.
315         * @see org.springframework.util.StringUtils#applyRelativePath(String, String)
316         */
317        @Override
318        public Resource createRelative(String relativePath) {
319                String pathToUse = StringUtils.applyRelativePath(this.path, relativePath);
320                return (this.file != null ? new FileSystemResource(pathToUse) :
321                                new FileSystemResource(this.filePath.getFileSystem(), pathToUse));
322        }
323
324        /**
325         * This implementation returns the name of the file.
326         * @see java.io.File#getName()
327         */
328        @Override
329        public String getFilename() {
330                return (this.file != null ? this.file.getName() : this.filePath.getFileName().toString());
331        }
332
333        /**
334         * This implementation returns a description that includes the absolute
335         * path of the file.
336         * @see java.io.File#getAbsolutePath()
337         */
338        @Override
339        public String getDescription() {
340                return "file [" + (this.file != null ? this.file.getAbsolutePath() : this.filePath.toAbsolutePath()) + "]";
341        }
342
343
344        /**
345         * This implementation compares the underlying File references.
346         */
347        @Override
348        public boolean equals(@Nullable Object other) {
349                return (this == other || (other instanceof FileSystemResource &&
350                                this.path.equals(((FileSystemResource) other).path)));
351        }
352
353        /**
354         * This implementation returns the hash code of the underlying File reference.
355         */
356        @Override
357        public int hashCode() {
358                return this.path.hashCode();
359        }
360
361}