2017-03-03 21 views
1

這是Eclipse的 執行我的代碼從這裏複製應用谷歌知識圖譜API。 io.FileNotFoundException:kgsearch.properties(沒有這樣的文件或目錄)錯誤。我如何在eclipse上獲得以下示例代碼?什麼是kgsearch.properties? <a href="https://developers.google.com/knowledge-graph/" rel="nofollow noreferrer">https://developers.google.com/knowledge-graph/</a></p> <p>與所有的庫安裝,該程序可以成功編譯,但 的Java終止程序:不能使用Java

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(); 
    } 
    } 
} 

回答

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)); 

它應該工作後記

閱讀有關類似問題here和示例here

相關問題