2

This is my code executed on Eclipse It is copied from here: https://developers.google.com/knowledge-graph/

with all libraries installed, the program can be compiled successfully, but the program terminated with java.io.FileNotFoundException: kgsearch.properties (No such file or directory) error. How can I get the following sample code work on my 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();
    }
  }
}
Robert Lui
  • 55
  • 5

1 Answers1

0

Yes because kgsearch.properties might not exists. Create the file and enter your API_KEY there. The file should look like

API_KEY = <your_key_here>

Once you have created and saved the file use the following code snippet

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

It should work afterwords

Read about a similar problem here and example here

Community
  • 1
  • 1
Anand Undavia
  • 3,493
  • 5
  • 19
  • 33