From 93447aa289cbf71bdd394cc216d5cdc14de25cff Mon Sep 17 00:00:00 2001 From: Dale Horton Date: Mon, 27 Jan 2014 13:06:46 +1100 Subject: [PATCH] CHANGED: Support non-English encodings by forcing UTF-8 support when accessing configuration files CHANGED: Check for access to parent folder and for read permission to the config file before opening the file for reading (prevents issues with virus scanners) Note: Implementation of both changes is loosely based on the mechanics of the MinecraftForge Configuration class. I'd suggest checking this for future reference. --- codechicken/lib/config/ConfigFile.java | 43 +++++++++++++++++++------- 1 file changed, 31 insertions(+), 12 deletions(-) diff --git a/codechicken/lib/config/ConfigFile.java b/codechicken/lib/config/ConfigFile.java index 6b84756..11d56c8 100644 --- a/codechicken/lib/config/ConfigFile.java +++ b/codechicken/lib/config/ConfigFile.java @@ -2,26 +2,43 @@ import java.io.BufferedReader; import java.io.File; +import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; +import java.io.InputStreamReader; import java.io.PrintWriter; +import java.io.UnsupportedEncodingException; + +import net.minecraftforge.common.Configuration.UnicodeInputStreamReader; public class ConfigFile extends ConfigTagParent { + public String defaultEncoding = "UTF-8"; + public ConfigFile(File file) { - if(!file.exists()) + try { - try + if (file.getParentFile() != null) { - file.createNewFile(); + file.getParentFile().mkdirs(); } - catch(IOException e) + + if (!file.exists() && !file.createNewFile()) { - throw new RuntimeException(e); + throw new IOException("Failed to create configuration file " + file.getCanonicalPath()); + } + + if(!file.canRead()) { + throw new IOException("Failed to read configuration file " + file.getCanonicalPath()); } } + catch(IOException e) + { + throw new RuntimeException(e); + } + this.file = file; newlinemode = 2; loadConfig(); @@ -31,11 +48,11 @@ private void loadConfig() { loading = true; BufferedReader reader; - try - { - reader = new BufferedReader(new FileReader(file)); - - while(true) + + try { + reader = new BufferedReader(new UnicodeInputStreamReader(new FileInputStream(file), defaultEncoding)); + + while(true) { reader.mark(2000); String line = reader.readLine(); @@ -127,12 +144,14 @@ public void saveConfig() PrintWriter writer; try { - writer = new PrintWriter(file); + writer = new PrintWriter(file, defaultEncoding); } catch(FileNotFoundException e) { throw new RuntimeException(e); - } + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } writeComment(writer, 0); ConfigFile.writeLine(writer, "", 0);