From 97bb827b9ed19e1f1663d7814d68a510a548e3f3 Mon Sep 17 00:00:00 2001 From: WakelessSloth56 Date: Thu, 31 Mar 2022 17:59:37 +0800 Subject: [PATCH] feat(utils): writeStringToFile method using UTF-8 charset --- .../mods/arnicalib/utils/java/FileUtils.java | 26 ++++++++++++------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/src/main/java/org/auioc/mods/arnicalib/utils/java/FileUtils.java b/src/main/java/org/auioc/mods/arnicalib/utils/java/FileUtils.java index e05c23c0..5bbe4f02 100644 --- a/src/main/java/org/auioc/mods/arnicalib/utils/java/FileUtils.java +++ b/src/main/java/org/auioc/mods/arnicalib/utils/java/FileUtils.java @@ -5,6 +5,7 @@ import java.io.File; import java.io.FileWriter; import java.io.IOException; +import java.nio.charset.Charset; import org.apache.logging.log4j.Marker; import org.auioc.mods.arnicalib.utils.LogUtil; @@ -15,9 +16,7 @@ public class FileUtils extends org.apache.commons.io.FileUtils { public static File getOrCreateDirectory(String directoryName) throws IOException { var file = new File(directoryName); - if (file.exists()) { - return file; - } + if (file.exists()) return file; if (file.mkdirs()) { LOGGER.warn(MARKER, "Directory \"" + file + "\" does not exist, create"); @@ -29,9 +28,7 @@ public static File getOrCreateDirectory(String directoryName) throws IOException public static File getFile(String fileName) throws IOException { var file = new File(fileName); - if (file.getParentFile().exists()) { - return file; - } + if (file.getParentFile().exists()) return file; if (file.getParentFile().mkdirs()) { LOGGER.warn(MARKER, "Parent directory of file \"" + file + "\" does not exist, create"); @@ -40,6 +37,19 @@ public static File getFile(String fileName) throws IOException { throw new IOException("Could not create parent directory of file \"" + file + "\""); } + + /** + * Writes a String to a file creating the file if it does not exist using the UTF-8 charset. + * + * @param file the file to write + * @param data the content to write to the file + * @throws IOException in case of an I/O error + * @since 5.1.4 + */ + public static void writeStringToFile(final File file, final String data) throws IOException { + writeStringToFile(file, data, Charset.forName("utf8"), false); + } + /* ============================================================================================================== */ // #region Deprecated @@ -50,9 +60,7 @@ private FileUtils() {} public static void writeText(String fileName, String text) throws IOException { var file = getFile(fileName); - if (file.exists()) { - LOGGER.warn(MARKER, "File \"" + file + "\" already exists, overwrite"); - } + if (file.exists()) LOGGER.warn(MARKER, "File \"" + file + "\" already exists, overwrite"); final var writer = new BufferedWriter(new FileWriter(file, false)); writer.write(text);