Skip to content

Commit

Permalink
JsonUtils: Always read the file using the UTF-8 charset. Also small c…
Browse files Browse the repository at this point in the history
…lean-up.
  • Loading branch information
maruohon committed Oct 22, 2021
1 parent 294d64b commit 0a19043
Showing 1 changed file with 4 additions and 22 deletions.
26 changes: 4 additions & 22 deletions src/main/java/fi/dy/masa/malilib/util/JsonUtils.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
package fi.dy.masa.malilib.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.Map;
Expand Down Expand Up @@ -415,13 +416,10 @@ public static JsonElement parseJsonFile(File file)
{
String fileName = file.getAbsolutePath();

try
try (InputStreamReader reader = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))
{
JsonParser parser = new JsonParser();
FileReader reader = new FileReader(file);

JsonElement element = parser.parse(reader);
reader.close();

return element;
}
Expand All @@ -436,17 +434,15 @@ public static JsonElement parseJsonFile(File file)

public static boolean writeJsonToFile(JsonObject root, File file)
{
OutputStreamWriter writer = null;
File fileTmp = new File(file.getParentFile(), file.getName() + ".tmp");

if (fileTmp.exists())
{
fileTmp = new File(file.getParentFile(), UUID.randomUUID() + ".tmp");
}

try
try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(fileTmp), StandardCharsets.UTF_8))
{
writer = new OutputStreamWriter(new FileOutputStream(fileTmp), StandardCharsets.UTF_8);
writer.write(GSON.toJson(root));
writer.close();

Expand All @@ -461,20 +457,6 @@ public static boolean writeJsonToFile(JsonObject root, File file)
{
MaLiLib.logger.warn("Failed to write JSON data to file '{}'", fileTmp.getAbsolutePath(), e);
}
finally
{
try
{
if (writer != null)
{
writer.close();
}
}
catch (Exception e)
{
MaLiLib.logger.warn("Failed to close JSON file", e);
}
}

return false;
}
Expand Down

0 comments on commit 0a19043

Please sign in to comment.