| 1 |
package gg.jte.convert; |
| 2 |
|
| 3 |
import java.io.BufferedWriter; |
| 4 |
import java.io.IOException; |
| 5 |
import java.io.UncheckedIOException; |
| 6 |
import java.nio.charset.StandardCharsets; |
| 7 |
import java.nio.file.Files; |
| 8 |
import java.nio.file.NoSuchFileException; |
| 9 |
import java.nio.file.Path; |
| 10 |
import java.nio.file.StandardCopyOption; |
| 11 |
import java.nio.file.StandardOpenOption; |
| 12 |
import java.util.stream.Stream; |
| 13 |
|
| 14 |
public final class IoUtils { |
| 15 |
|
| 16 |
private IoUtils() { |
| 17 |
} |
| 18 |
|
| 19 |
public static String readFile(Path file) { |
| 20 |
try { |
| 21 |
return new String(Files.readAllBytes(file), StandardCharsets.UTF_8); |
| 22 |
} catch (IOException e) { |
| 23 |
throw new UncheckedIOException(e); |
| 24 |
} |
| 25 |
} |
| 26 |
|
| 27 |
public static void writeFile(Path file, String content) { |
| 28 |
try { |
| 29 |
Files.createDirectories(file.getParent()); |
| 30 |
try (BufferedWriter writer = Files.newBufferedWriter(file, StandardCharsets.UTF_8, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE)) { |
| 31 |
writer.write(content); |
| 32 |
} |
| 33 |
} catch (IOException e) { |
| 34 |
throw new UncheckedIOException(e); |
| 35 |
} |
| 36 |
} |
| 37 |
|
| 38 |
public static void copyDirectory(Path src, Path dest) { |
| 39 |
try { |
| 40 |
try (Stream<Path> stream = Files.walk(src)) { |
| 41 |
stream.forEach(f -> copy(f, dest.resolve(src.relativize(f)))); |
| 42 |
} |
| 43 |
} catch (IOException e) { |
| 44 |
throw new UncheckedIOException(e); |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
private static void copy(Path src, Path dst) { |
| 49 |
try { |
| 50 |
Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING); |
| 51 |
} catch (IOException e) { |
| 52 |
throw new UncheckedIOException(e); |
| 53 |
} |
| 54 |
} |
| 55 |
|
| 56 |
public static void deleteFile(Path file) { |
| 57 |
try { |
| 58 |
Files.delete(file); |
| 59 |
} catch ( NoSuchFileException e ) { |
| 60 |
// Okay, it is already deleted. |
| 61 |
} catch (IOException e) { |
| 62 |
throw new UncheckedIOException(e); |
| 63 |
} |
| 64 |
} |
| 65 |
} |