2

这是我在 Eclipse 上执行的代码它是从这里复制的: https ://developers.google.com/knowledge-graph/

安装所有库后,程序可以成功编译,但程序以 java.io.FileNotFoundException: kgsearch.properties (No such file or directory) 错误终止。如何让以下示例代码在我的 eclipse 上运行?

import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;

import com.jayway.jsonpath.JsonPath;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

import java.io.FileInputStream;
import java.util.Properties;

public class mainS {
  public static Properties properties = new Properties();
  public static void main(String[] args) {
    try {
      properties.load(new FileInputStream("kgsearch.properties"));

      HttpTransport httpTransport = new NetHttpTransport();
      HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
      JSONParser parser = new JSONParser();
      GenericUrl url = new GenericUrl("https://kgsearch.googleapis.com/v1/entities:search");
      url.put("query", "Taylor Swift");
      url.put("limit", "10");
      url.put("indent", "true");
      url.put("key", properties.get("API_KEY"));
      HttpRequest request = requestFactory.buildGetRequest(url);
      HttpResponse httpResponse = request.execute();
      JSONObject response = (JSONObject) parser.parse(httpResponse.parseAsString());
      JSONArray elements = (JSONArray) response.get("itemListElement");
      for (Object element : elements) {
        System.out.println(JsonPath.read(element, "$.result.name").toString());
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
}
4

1 回答 1

0

是的,因为kgsearch.properties可能不存在。创建文件并在此处输入您的 API_KEY。该文件应该看起来像

API_KEY = <your_key_here>

创建并保存文件后,使用以下代码片段

File file = new File("C:/your/path/here/", "kgsearch.properties");
properties.load(new FileInputStream(file));

它应该在后面起作用

在此处阅读类似问题并此处阅读示例

于 2017-03-03T06:28:23.617 回答