昨天做了个项目,其中有个需求是,需要获取全国高校及其对应的code,我从网上扒拉下来了json格式的字符串
数据,但是需要通过代码把他存到数据库里面,本来想着直接把他直接粘贴到工程里面直接转成json对象,但是报错了,像这样
所以就想起来先把数据写到本地文件,然后再通过流的方式读入到工程中,然后转换成json对象即可,如下:
/**
* 根据文件路径读取字符串
* @param url
* @throws IOException
*/
public static String getStringByFile(String url) {
BufferedReader reader;
StringBuilder stringBuilder = new StringBuilder();
try {
reader = new BufferedReader(new FileReader(url));
stringBuilder = new StringBuilder();
String line;
String ls = System.getProperty("line.separator");
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(ls);
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
return stringBuilder.toString();
}
/**
* 获取全国高校列表
* colleges and universities
* @return
*/
public static JSONArray getColAndUni() {
String school = getStringByFile("D://全国高校code.json");
JSONObject schoolObj = JSONObject.parseObject(school);
JSONArray ds = schoolObj.getJSONArray("ds");
for(int i=0;i<ds.size();i++) {
JSONObject temp = ds.getJSONObject(i);
temp.put("size", temp.getJSONArray("data").size());
}
return ds;
}
public static void main(String[] args) {
System.out.println(getColAndUni());
}
```
其中有个值得注意的地方是,读取文件时,stringBuilder.append(ls); 这行代码是在读取完一行之后换行使用,如果注释掉的话,读取出的数据就会挤在一行里面了,如图:
所以这时候需要在读取一行之后增加换行符。