Debian Codegraph @

src/main/org/h2/store/fs/FileUtils.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.store.fs;
7
8 import java.io.BufferedReader;
9 import java.io.EOFException;
10 import java.io.File;
11 import java.io.IOException;
12 import java.io.InputStream;
13 import java.io.InputStreamReader;
14 import java.io.OutputStream;
15 import java.nio.ByteBuffer;
16 import java.nio.channels.FileChannel;
17 import java.nio.charset.Charset;
18 import java.nio.file.OpenOption;
19 import java.nio.file.StandardOpenOption;
20 import java.nio.file.attribute.FileAttribute;
21 import java.util.ArrayList;
22 import java.util.Collections;
23 import java.util.EnumSet;
24 import java.util.List;
25 import java.util.Set;
26
27 import org.h2.engine.Constants;
28
29 /**
30 * This utility class contains utility functions that use the file system
31 * abstraction.
32 */
33 public class FileUtils {
34
35 /**
36 * {@link StandardOpenOption#READ}.
37 */
38 public static final Set<? extends OpenOption> R = Collections.singleton(StandardOpenOption.READ);
39
40 /**
41 * {@link StandardOpenOption#READ}, {@link StandardOpenOption#WRITE}, and
42 * {@link StandardOpenOption#CREATE}.
43 */
44 public static final Set<? extends OpenOption> RW = Collections
45 .unmodifiableSet(EnumSet.of(StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE));
46
47 /**
48 * {@link StandardOpenOption#READ}, {@link StandardOpenOption#WRITE},
49 * {@link StandardOpenOption#CREATE}, and {@link StandardOpenOption#SYNC}.
50 */
51 public static final Set<? extends OpenOption> RWS = Collections.unmodifiableSet(EnumSet.of(StandardOpenOption.READ,
52 StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.SYNC));
53
54 /**
55 * {@link StandardOpenOption#READ}, {@link StandardOpenOption#WRITE},
56 * {@link StandardOpenOption#CREATE}, and {@link StandardOpenOption#DSYNC}.
57 */
58 public static final Set<? extends OpenOption> RWD = Collections.unmodifiableSet(EnumSet.of(StandardOpenOption.READ,
59 StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.DSYNC));
60
61 /**
62 * No file attributes.
63 */
64 public static final FileAttribute<?>[] NO_ATTRIBUTES = new FileAttribute[0];
65
66 /**
67 * Checks if a file exists.
68 * This method is similar to Java 7 <code>java.nio.file.Path.exists</code>.
69 *
70 * @param fileName the file name
71 * @return true if it exists
72 */
73 public static boolean exists(String fileName) {
74 return FilePath.get(fileName).exists();
75 }
76
77 /**
78 * Create a directory (all required parent directories must already exist).
79 * This method is similar to Java 7
80 * <code>java.nio.file.Path.createDirectory</code>.
81 *
82 * @param directoryName the directory name
83 */
84 public static void createDirectory(String directoryName) {
85 FilePath.get(directoryName).createDirectory();
86 }
87
88 /**
89 * Create a new file. This method is similar to Java 7
90 * <code>java.nio.file.Path.createFile</code>, but returns false instead of
91 * throwing a exception if the file already existed.
92 *
93 * @param fileName the file name
94 * @return true if creating was successful
95 */
96 public static boolean createFile(String fileName) {
97 return FilePath.get(fileName).createFile();
98 }
99
100 /**
101 * Delete a file or directory if it exists.
102 * Directories may only be deleted if they are empty.
103 * This method is similar to Java 7
104 * <code>java.nio.file.Path.deleteIfExists</code>.
105 *
106 * @param path the file or directory name
107 */
108 public static void delete(String path) {
109 FilePath.get(path).delete();
110 }
111
112 /**
113 * Get the canonical file or directory name. This method is similar to Java
114 * 7 <code>java.nio.file.Path.toRealPath</code>.
115 *
116 * @param fileName the file name
117 * @return the normalized file name
118 */
119 public static String toRealPath(String fileName) {
120 return FilePath.get(fileName).toRealPath().toString();
121 }
122
123 /**
124 * Get the parent directory of a file or directory. This method returns null
125 * if there is no parent. This method is similar to Java 7
126 * <code>java.nio.file.Path.getParent</code>.
127 *
128 * @param fileName the file or directory name
129 * @return the parent directory name
130 */
131 public static String getParent(String fileName) {
132 FilePath p = FilePath.get(fileName).getParent();
133 return p == null ? null : p.toString();
134 }
135
136 /**
137 * Check if the file name includes a path. This method is similar to Java 7
138 * <code>java.nio.file.Path.isAbsolute</code>.
139 *
140 * @param fileName the file name
141 * @return if the file name is absolute
142 */
143 public static boolean isAbsolute(String fileName) {
144 return FilePath.get(fileName).isAbsolute()
145 // Allows Windows to recognize "/path" as absolute.
146 // Makes the same configuration work on all platforms.
147 || fileName.startsWith(File.separator)
148 // Just in case of non-normalized path on Windows
149 || fileName.startsWith("/");
150 }
151
152 /**
153 * Rename a file if this is allowed. This method is similar to Java 7
154 * <code>java.nio.file.Files.move</code>.
155 *
156 * @param source the old fully qualified file name
157 * @param target the new fully qualified file name
158 */
159 public static void move(String source, String target) {
160 FilePath.get(source).moveTo(FilePath.get(target), false);
161 }
162
163 /**
164 * Rename a file if this is allowed, and try to atomically replace an
165 * existing file. This method is similar to Java 7
166 * <code>java.nio.file.Files.move</code>.
167 *
168 * @param source the old fully qualified file name
169 * @param target the new fully qualified file name
170 */
171 public static void moveAtomicReplace(String source, String target) {
172 FilePath.get(source).moveTo(FilePath.get(target), true);
173 }
174
175 /**
176 * Get the file or directory name (the last element of the path).
177 * This method is similar to Java 7 <code>java.nio.file.Path.getName</code>.
178 *
179 * @param path the directory and file name
180 * @return just the file name
181 */
182 public static String getName(String path) {
183 return FilePath.get(path).getName();
184 }
185
186 /**
187 * List the files and directories in the given directory.
188 * This method is similar to Java 7
189 * <code>java.nio.file.Path.newDirectoryStream</code>.
190 *
191 * @param path the directory
192 * @return the list of fully qualified file names
193 */
194 public static List<String> newDirectoryStream(String path) {
195 List<FilePath> list = FilePath.get(path).newDirectoryStream();
196 int len = list.size();
197 List<String> result = new ArrayList<>(len);
198 for (FilePath filePath : list) {
199 result.add(filePath.toString());
200 }
201 return result;
202 }
203
204 /**
205 * Get the last modified date of a file.
206 * This method is similar to Java 7
207 * <code>java.nio.file.attribute.Attributes.
208 * readBasicFileAttributes(file).lastModified().toMillis()</code>
209 *
210 * @param fileName the file name
211 * @return the last modified date
212 */
213 public static long lastModified(String fileName) {
214 return FilePath.get(fileName).lastModified();
215 }
216
217 /**
218 * Get the size of a file in bytes
219 * This method is similar to Java 7
220 * <code>java.nio.file.attribute.Attributes.
221 * readBasicFileAttributes(file).size()</code>
222 *
223 * @param fileName the file name
224 * @return the size in bytes
225 */
226 public static long size(String fileName) {
227 return FilePath.get(fileName).size();
228 }
229
230 /**
231 * Check if it is a file or a directory.
232 * <code>java.nio.file.attribute.Attributes.
233 * readBasicFileAttributes(file).isDirectory()</code>
234 *
235 * @param fileName the file or directory name
236 * @return true if it is a directory
237 */
238 public static boolean isDirectory(String fileName) {
239 return FilePath.get(fileName).isDirectory();
240 }
241
242 /**
243 * Tests whether a file is a regular file.
244 *
245 * @param fileName the file or directory name
246 * @return true if it is a regular file
247 */
248 public static boolean isRegularFile(String fileName) {
249 return FilePath.get(fileName).isRegularFile();
250 }
251
252 /**
253 * Open a random access file object.
254 * This method is similar to Java 7
255 * <code>java.nio.channels.FileChannel.open</code>.
256 *
257 * @param fileName the file name
258 * @param mode the access mode. Supported are r, rw, rws, rwd
259 * @return the file object
260 * @throws IOException on failure
261 */
262 public static FileChannel open(String fileName, String mode)
263 throws IOException {
264 return FilePath.get(fileName).open(mode);
265 }
266
267 /**
268 * Create an input stream to read from the file.
269 * This method is similar to Java 7
270 * <code>java.nio.file.Files.newInputStream()</code>.
271 *
272 * @param fileName the file name
273 * @return the input stream
274 * @throws IOException on failure
275 */
276 public static InputStream newInputStream(String fileName) throws IOException {
277 return FilePath.get(fileName).newInputStream();
278 }
279
280 /**
281 * Create a buffered reader to read from the file.
282 * This method is similar to
283 * <code>java.nio.file.Files.newBufferedReader()</code>.
284 *
285 * @param fileName the file name
286 * @param charset the charset
287 * @return the buffered reader
288 * @throws IOException on failure
289 */
290 public static BufferedReader newBufferedReader(String fileName, Charset charset) throws IOException {
291 return new BufferedReader(new InputStreamReader(newInputStream(fileName), charset), Constants.IO_BUFFER_SIZE);
292 }
293
294 /**
295 * Create an output stream to write into the file.
296 * This method is similar to
297 * <code>java.nio.file.Files.newOutputStream()</code>.
298 *
299 * @param fileName the file name
300 * @param append if true, the file will grow, if false, the file will be
301 * truncated first
302 * @return the output stream
303 * @throws IOException on failure
304 */
305 public static OutputStream newOutputStream(String fileName, boolean append) throws IOException {
306 return FilePath.get(fileName).newOutputStream(append);
307 }
308
309 /**
310 * Check if the file is writable.
311 * This method is similar to Java 7
312 * <code>java.nio.file.Path.checkAccess(AccessMode.WRITE)</code>
313 *
314 * @param fileName the file name
315 * @return if the file is writable
316 */
317 public static boolean canWrite(String fileName) {
318 return FilePath.get(fileName).canWrite();
319 }
320
321 // special methods =======================================
322
323 /**
324 * Disable the ability to write. The file can still be deleted afterwards.
325 *
326 * @param fileName the file name
327 * @return true if the call was successful
328 */
329 public static boolean setReadOnly(String fileName) {
330 return FilePath.get(fileName).setReadOnly();
331 }
332
333 /**
334 * Get the unwrapped file name (without wrapper prefixes if wrapping /
335 * delegating file systems are used).
336 *
337 * @param fileName the file name
338 * @return the unwrapped
339 */
340 public static String unwrap(String fileName) {
341 return FilePath.get(fileName).unwrap().toString();
342 }
343
344 // utility methods =======================================
345
346 /**
347 * Delete a directory or file and all subdirectories and files.
348 *
349 * @param path the path
350 * @param tryOnly whether errors should be ignored
351 */
352 public static void deleteRecursive(String path, boolean tryOnly) {
353 if (exists(path)) {
354 if (isDirectory(path)) {
355 for (String s : newDirectoryStream(path)) {
356 deleteRecursive(s, tryOnly);
357 }
358 }
359 if (tryOnly) {
360 tryDelete(path);
361 } else {
362 delete(path);
363 }
364 }
365 }
366
367 /**
368 * Create the directory and all required parent directories.
369 *
370 * @param dir the directory name
371 */
372 public static void createDirectories(String dir) {
373 if (dir != null) {
374 if (exists(dir)) {
375 if (!isDirectory(dir)) {
376 // this will fail
377 createDirectory(dir);
378 }
379 } else {
380 String parent = getParent(dir);
381 createDirectories(parent);
382 createDirectory(dir);
383 }
384 }
385 }
386
387 /**
388 * Try to delete a file or directory (ignoring errors).
389 *
390 * @param path the file or directory name
391 * @return true if it worked
392 */
393 public static boolean tryDelete(String path) {
394 try {
395 FilePath.get(path).delete();
396 return true;
397 } catch (Exception e) {
398 return false;
399 }
400 }
401
402 /**
403 * Create a new temporary file.
404 *
405 * @param prefix the prefix of the file name (including directory name if
406 * required)
407 * @param suffix the suffix
408 * @param inTempDir if the file should be stored in the temporary directory
409 * @return the name of the created file
410 * @throws IOException on failure
411 */
412 public static String createTempFile(String prefix, String suffix,
413 boolean inTempDir) throws IOException {
414 return FilePath.get(prefix).createTempFile(suffix, inTempDir).toString();
415 }
416
417 /**
418 * Fully read from the file. This will read all remaining bytes,
419 * or throw an EOFException if not successful.
420 *
421 * @param channel the file channel
422 * @param dst the byte buffer
423 * @throws IOException on failure
424 */
425 public static void readFully(FileChannel channel, ByteBuffer dst)
426 throws IOException {
427 do {
428 int r = channel.read(dst);
429 if (r < 0) {
430 throw new EOFException();
431 }
432 } while (dst.remaining() > 0);
433 }
434
435 /**
436 * Fully write to the file. This will write all remaining bytes.
437 *
438 * @param channel the file channel
439 * @param src the byte buffer
440 * @throws IOException on failure
441 */
442 public static void writeFully(FileChannel channel, ByteBuffer src)
443 throws IOException {
444 do {
445 channel.write(src);
446 } while (src.remaining() > 0);
447 }
448
449 /**
450 * Convert the string representation to a set.
451 *
452 * @param mode the mode as a string
453 * @return the set
454 */
455 public static Set<? extends OpenOption> modeToOptions(String mode) {
456 Set<? extends OpenOption> options;
457 switch (mode) {
458 case "r":
459 options = R;
460 break;
461 case "rw":
462 options = RW;
463 break;
464 case "rws":
465 options = RWS;
466 break;
467 case "rwd":
468 options = RWD;
469 break;
470 default:
471 throw new IllegalArgumentException(mode);
472 }
473 return options;
474 }
475
476 }