1
我正在使用java调用REST API Get方法,并且需要将JSON数据存储到文件中。 这里是我的JSON数据:使用Java将JSON数据推送到文件中
{
"took" : 25,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"failed" : 0
},
"hits" : {
"total" : 820,
"max_score" : 1.0,
"hits" : [ {
"_index" : "test",
"_type" : "status",
"_id" : "abc-2345-dadasasdasd214124",
"_score" : 1.0,
"_source":
{"A":1,"B":12,"C":122,"D":89,"E":120,"F":100,"G":2}
}, {
"_index" : "test",
"_type" : "status",
"_id" : "abc-2345-dadasasdasd214124",
"_score" : 1.0,
"_source":
{"A":54,"B":171,"C":102,"D":0,"E":120,"F":11,"G":20}
} , {
"_index" : "test",
"_type" : "status",
"_id" : "abc-2345-dadasasdasd214124",
"_score" : 1.0,
"_source":
{"A":94,"B":8,"C":155,"D":32,"E":90,"F":11,"G":0}
} ]
}
}
这里是我的代码:
public class testcode {
public static void main(String[] args) throws ClientProtocolException, IOException {
HttpClient client = new DefaultHttpClient();
try {
HttpGet httpGetRequest = new HttpGet("http://localhost:8080/test_search?pretty=1");
HttpResponse httpResponse = client.execute(httpGetRequest);
HttpEntity entity = httpResponse.getEntity();
byte[] buffer = new byte[1024];
if (entity != null) {
InputStream inputStream = entity.getContent();
try {
int bytesRead = 0;
BufferedInputStream bis = new BufferedInputStream(inputStream);
FileWriter file = new FileWriter("/path/test.json");
while ((bytesRead = bis.read(buffer)) != -1) {
String chunk = new String(buffer, 0, bytesRead);
System.out.println(chunk);
file.write(chunk);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try { inputStream.close(); } catch (Exception ignore) {}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
client.getConnectionManager().shutdown();
}
}
运行此代码后,我看到了JSON数据在我的控制台,但整个数据是没有得到保存到test.json文件。前两个数组完全保存,但只有第三个数组的一部分被保存到test.json中。
数据在test.json文件:
{
"took" : 25,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"failed" : 0
},
"hits" : {
"total" : 820,
"max_score" : 1.0,
"hits" : [ {
"_index" : "test",
"_type" : "status",
"_id" : "abc-2345-dadasasdasd214124",
"_score" : 1.0,
"_source":
{"A":1,"B":12,"C":122,"D":89,"E":120,"F":100,"G":2}
}, {
"_index" : "test",
"_type" : "status",
"_id" : "abc-2345-dadasasdasd214124",
"_score" : 1.0,
"_source":
{"A":54,"B":171,"C":102,"D":0,"E":120,"F":11,"G":20}
} , {
"_index" : "test",
"_type" : "status",
"_id" : "abc-2345-dadasasdasd214124",
"_score" : 1.0,
"_source":
{"A":94,"B":8,"C":155,"D":32,"E
注:上面给出JSON数据是一个样本数据。真正的json文件包含大量数据。请指教。谢谢
很酷,工作。非常感谢。 – Sweet