方法一:(utf-8编码格式的文件)
如下代码:
参数pactFile为json文件存放的位置
使用方式:可以将下面方法放到一个工具类中,使用时调用此方法并传入保存文件存放位置的变量pactFile
/**
* 读取json文件并且转换成字符串
* @param filePath文件的路径
* @return
* @throws IOException
*/
public static String readJsonData(String pactFile) throws IOException {
// 读取文件数据
//System.out.println("读取文件数据util");
StringBuffer strbuffer = new StringBuffer();
File myFile = new File(pactFile);//"D:"+File.separatorChar+"DStores.json"
if (!myFile.exists()) {
System.err.println("Can't Find " + pactFile);
}
try {
FileInputStream fis = new FileInputStream(pactFile);
InputStreamReader inputStreamReader = new InputStreamReader(fis, "UTF-8");
BufferedReader in = new BufferedReader(inputStreamReader);
String str;
while ((str = in.readLine()) != null) {
strbuffer.append(str); //new String(str,"UTF-8")
}
in.close();
} catch (IOException e) {
e.getStackTrace();
}
//System.out.println("读取文件结束util");
return strbuffer.toString();
}
方式二:(GBK编码方式的json文件)
使用方式同上
/**
* 读取json文件并且转换成字符串(读取GBK编码方式的)
* @param filePath文件的路径
* @return
* @throws IOException
*/
public static String readJsonGBK(String pactFile) throws IOException {
// 读取文件数据
//System.out.println("读取文件数据util");
StringBuffer strbuffer = new StringBuffer();
File myFile = new File(pactFile);//"D:"+File.separatorChar+"DStores.json"
if (!myFile.exists()) {
System.err.println("Can't Find " + pactFile);
}
try {
FileInputStream fis = new FileInputStream(pactFile);
InputStreamReader inputStreamReader = new InputStreamReader(fis, "GBK");
BufferedReader in = new BufferedReader(inputStreamReader);
String str;
while ((str = in.readLine()) != null) {
strbuffer.append(str); //new String(str,"UTF-8")
}
in.close();
} catch (IOException e) {
e.getStackTrace();
}
//System.out.println("读取文件结束util");
return strbuffer.toString();
}