执行YahooFinance.get时触发java.io.FileNotFoundException的替代方案咨询
可行替代方案
1. 升级或更换维护中的Yahoo Finance第三方库
你之前使用的Yahoo Finance库可能未适配Yahoo接口的最新访问限制,可尝试更换为社区仍在维护的分支版本(部分fork库已修复接口访问问题)。调整依赖后,原有代码逻辑基本无需修改,只需确保引入的是更新后的库。
2. 切换至其他免费股票数据API
Alpha Vantage
提供免费的股票实时/历史数据接口,需先申请免费API密钥(额度足够个人项目使用)。示例代码如下:
import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public static double getStockCurrentPrice(String stockSymbol) { String apiKey = "你的免费API密钥"; String requestUrl = String.format("https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=%s&apikey=%s", stockSymbol, apiKey); double currentPrice = 0.0; try { URL url = new URL(requestUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); JSONObject responseJson = new JSONObject(response.toString()); JSONObject globalQuote = responseJson.getJSONObject("Global Quote"); currentPrice = Double.parseDouble(globalQuote.getString("05. price")); } catch (Exception e) { System.err.println("Symbol Name: " + stockSymbol); e.printStackTrace(); } return currentPrice; }
需添加JSON解析依赖(如Gradle:implementation 'org.json:json:20231013')。
Polygon.io
免费层提供每日限量的实时股票数据,接口稳定性较好。核心逻辑与上述示例类似,只需替换请求URL和JSON解析规则即可。
3. 临时异常修复(治标不治本)
若需临时维持原有逻辑,需先修复空指针问题:在price.doubleValue()前判断price是否为null,避免崩溃。但这无法解决接口访问失败的根本问题,仅作为过渡方案:
Double curr_price = price != null ? price.doubleValue() : 0.0; // 或抛出自定义业务异常 return curr_price;
内容的提问来源于stack exchange,提问作者markke
相关产品推荐
相关产品推荐

