So I am using json to store some data in a txt file. And I use Gson to tackle json. The program went well in eclipse. But when I packaged it into a jar, problem occrurs.
What I did first (in eclipse) is:
String gsonStr = gson.toJson(masterShips);
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter("D:\\master_ship.txt"));
writer.write(gsonStr);
} catch (IOException e) {
System.err.println(e);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
System.err.println(e);
}
}
}
Then I copied the .txt file to eclipse and read it using this code:
Scanner in = new Scanner(new FileReader("master_ship.txt"));
String str = in.nextLine();
Log.toDebug(str);
in.close();
JsonParser parser = new JsonParser();
JsonElement je = parser.parse(str);
JsonArray ja = je.getAsJsonArray();
for (int i=0; i<ja.size(); ++i) {
...
}
But when I put the .jar file and the .txt file in the same folder and excute, error appear. I thought there may be problems with the way of defining the path. Finally I turned to absolute path:
Scanner in = new Scanner(new FileReader("D:\\master_ship.txt"));
Still, it works well in eclipse, but not when using jar. Then I opened the jar with command line:
Exception in thread "main" com.google.gson.JsonSyntaxException: com.google.gson.
stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malform
ed JSON at line 1 column 4
at com.google.gson.JsonParser.parse(JsonParser.java:65)
at com.google.gson.JsonParser.parse(JsonParser.java:45)
at kan.util.Master.loadMasterShip(Master.java:44)
at kan.util.Master.load(Master.java:27)
at kan.Main.main(Main.java:22)
Caused by: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLeni
ent(true) to accept malformed JSON at line 1 column 4
at com.google.gson.stream.JsonReader.syntaxError(JsonReader.java:1505)
at com.google.gson.stream.JsonReader.checkLenient(JsonReader.java:1386)
at com.google.gson.stream.JsonReader.doPeek(JsonReader.java:531)
at com.google.gson.stream.JsonReader.peek(JsonReader.java:414)
at com.google.gson.JsonParser.parse(JsonParser.java:60)
... 4 more
I can be sure that the file is read successfully, because the jar can output the string it read from the file completely. But why should Gson fail outside eclipse while doing good in eclipse.