-
-
Notifications
You must be signed in to change notification settings - Fork 836
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
2b23c2a
commit 3b32e67
Showing
2 changed files
with
57 additions
and
24 deletions.
There are no files selected for viewing
50 changes: 50 additions & 0 deletions
50
worldedit-core/src/main/java/com/sk89q/worldedit/util/io/file/SafeFiles.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
package com.sk89q.worldedit.util.io.file; | ||
|
||
import java.io.IOException; | ||
import java.nio.file.Files; | ||
import java.nio.file.Path; | ||
import java.util.List; | ||
import java.util.stream.Collectors; | ||
import java.util.stream.Stream; | ||
|
||
public class SafeFiles { | ||
|
||
/** | ||
* A version of {@link Files#list(Path)} that won't leak resources. | ||
* | ||
* <p> | ||
* Instead, it immediately consumes the entire listing into a {@link List} and | ||
* calls {@link List#stream()}. | ||
* </p> | ||
* | ||
* @param dir the directory to list | ||
* @return an I/O-resource-free stream of the files in the directory | ||
* @throws IOException if an I/O error occurs | ||
*/ | ||
public static Stream<Path> noLeakFileList(Path dir) throws IOException { | ||
try (Stream<Path> stream = Files.list(dir)) { | ||
return stream.collect(Collectors.toList()).stream(); | ||
} | ||
} | ||
|
||
/** | ||
* {@link Path#getFileName()} includes a slash sometimes for some reason. | ||
* This will get rid of it. | ||
* | ||
* @param path the path to get the file name for | ||
* @return the file name of the given path | ||
*/ | ||
public static String canonicalFileName(Path path) { | ||
return dropSlash(path.getFileName().toString()); | ||
} | ||
|
||
private static String dropSlash(String name) { | ||
if (name.isEmpty() || name.codePointBefore(name.length()) != '/') { | ||
return name; | ||
} | ||
return name.substring(0, name.length() - 1); | ||
} | ||
|
||
private SafeFiles() { | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters