读取src目录下的json文件
/**
* 读取json文件,返回json串
* @param fileName
* @return
*/
private static String readJsonFile(String fileName) {
String jsonStr = "";
try {
File jsonFile = ResourceUtils.getFile(fileName);
FileReader fileReader = new FileReader(jsonFile);
Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
fileReader.close();
reader.close();
jsonStr = sb.toString();
return jsonStr;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
String path = System.getProperty("user.dir") + "/src/main/java/com/awb/controller/center/city.json";
String jsonFile = readJsonFile(path);
读取网络文件
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
......
public static String openFile(String filePath) {
int HttpResult; // 服务器返回的状态
String ee = new String();
try
{
URL url =new URL(filePath); // 创建URL
URLConnection urlconn = url.openConnection(); // 试图连接并取得返回状态码
urlconn.connect();
HttpURLConnection httpconn =(HttpURLConnection)urlconn;
HttpResult = httpconn.getResponseCode();
if(HttpResult != HttpURLConnection.HTTP_OK) {
System.out.print("无法连接到");
} else {
int filesize = urlconn.getContentLength(); // 取数据长度
InputStreamReader isReader = new InputStreamReader(urlconn.getInputStream(),"UTF-8");
BufferedReader reader = new BufferedReader(isReader);
StringBuffer buffer = new StringBuffer();
String line; // 用来保存每行读取的内容
line = reader.readLine(); // 读取第一行
while (line != null) { // 如果 line 为空说明读完了
buffer.append(line); // 将读到的内容添加到 buffer 中
buffer.append(" "); // 添加换行符
line = reader.readLine(); // 读取下一行
}
System.out.print(buffer.toString());
ee = buffer.toString();
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return ee;
}
public static void main(String[] args) {
String path = "https://xxx/city.json";
System.out.println(FileUtil.openFile(path));
}