Recently, I encountered a problem when developing a project. I used googlede gson on myecilpes to read the json file in the project successfully, and then published the project to tomcat and then used the same method. It will prompt "The system cannot find the specified path"
Place the file under src/config/
JsonParser parser = new JsonParser(); JsonObject object = (JsonObject) parser.parse(new FileReader("config/Test.json"));After searching for many articles, I found that the problem should be that after publishing to the server, the relative path of the file is not found, so I can only use the absolute path to find the project Test under the webapps of tomcat
The path is
D:/Program Files/Tomcat 8.0/webapps/Test/WEB-INF/classes/Test.json
After modifying the read path, you can read to the json file. The following is the method to obtain the absolute path in a separate Java class. Because there are spaces in the folder, I replaced the space part of the spaces that were changed.
String path = JsonUtil.class.getClassLoader().getResource("/Test.json").getPath().replace("%20", " ");JsonParser parser = new JsonParser(); JsonObject object = (JsonObject) parser.parse(new FileReader(path ));However, the content read in this way is garbled. The reason may be that the system encoding format is inconsistent with the compiler's encoding format, so I used streaming to read the file instead
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.Reader;import java.util.ArrayList;import java.util.List;import com.google.gson.JsonArray;import com.google.gson.JsonIOException;import com.google.gson.JsonObject;import com.google.gson.JsonParser;import com.google.gson.JsonSyntaxException;/** * @author LK */public class JsonUtil {/** * Read the local json file and get the json format string * @return */ public static String getJsonString(){ String path = JsonUtil.class.getClassLoader().getResource("/Test.json").getPath().replace("%20", " "); File file = new File(path); try { FileReader fileReader = new FileReader(file); Reader reader = new InputStreamReader(new FileInputStream(file),"utf-8"); int ch = 0; StringBuffer sb = new StringBuffer(); while ((ch = reader.read()) != -1) { sb.append((char) ch); } fileReader.close(); reader.close(); String jsonString = sb.toString(); return jsonString; } catch (IOException e) { e.printStackTrace(); return null; } }}Then parse the obtained json format String
String jsonString = JsonUtil.getJsonString();JsonParser parser = new JsonParser(); JsonObject object = (JsonObject) parser.parse(jsonString);
This way you can get the correct JsonObject
The above article solves the problem of JavaWeb reading local json files and garbled codes. This is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.