这是我在Eclipse上执行的代码从这里复制:https://developers.google.com/knowledge-graph/
在安装了所有库后,可以成功编译该程序,但是该程序终止java.io.filenotfoundexception:kgsearch.properties(没有这样的文件或目录)错误。我如何在日食上获得以下示例代码工作?
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();
}
}
}
是的,因为kgsearch.properties
可能不存在。创建文件并在此处输入您的API_KEY。该文件应该看起来像
API_KEY = <your_key_here>
创建并保存文件后,请使用以下代码段
File file = new File("C:/your/path/here/", "kgsearch.properties");
properties.load(new FileInputStream(file));
它应该使用后词
在此处阅读有关类似问题的信息,此处示例