gpt4 book ai didi

java - URLConnection 的错误处理

转载 作者:行者123 更新时间:2023-12-01 15:35:43 26 4
gpt4 key购买 nike

我有这种方法,可以从雅虎财经下载 .csv 文件并将其保存在本地。它是在循环期间访问的,因此它从列表中下载许多文件。然而,有时符号输入不正确、不再存在或连接超时。如何修改此方法,以便重试连接超时并跳过不正确的符号(意味着网址不起作用)而不结束程序?

public static void get_file(String symbol){

OutputStream outStream = null;
URLConnection uCon = null;
InputStream is = null;

String finance_url = "http://ichart.finance.yahoo.com/table.csv?s="+symbol;
String destination = "C:/"+symbol+"_table.csv";

try {
URL Url;
byte[] buf;
int ByteRead,ByteWritten=0;
Url= new URL(finance_url);

outStream = new BufferedOutputStream(new FileOutputStream(destination));

uCon = Url.openConnection();
is = uCon.getInputStream();
buf = new byte[size];

while ((ByteRead = is.read(buf)) != -1) {
outStream.write(buf, 0, ByteRead);
ByteWritten += ByteRead;
}

}catch (Exception e) {
System.out.println("Error while downloading "+symbol);
e.printStackTrace();
}finally {
try {
is.close();
outStream.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}

最佳答案

为什么不在抛出异常时再次调用该方法呢?您可以缩小异常类型的范围以指示何时应启动重试。

public static void get_file(String symbol){

OutputStream outStream = null;
URLConnection uCon = null;
InputStream is = null;

String finance_url = "http://ichart.finance.yahoo.com/table.csv?s="+symbol;
String destination = "C:/"+symbol+"_table.csv";

try {
URL Url;
byte[] buf;
int ByteRead,ByteWritten=0;
Url= new URL(finance_url);

outStream = new BufferedOutputStream(new FileOutputStream(destination));

uCon = Url.openConnection();
is = uCon.getInputStream();
buf = new byte[size];

while ((ByteRead = is.read(buf)) != -1) {
outStream.write(buf, 0, ByteRead);
ByteWritten += ByteRead;
}

}catch (Exception e) {
getFile(symbol);
}finally {
try {
is.close();
outStream.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}

关于java - URLConnection 的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8882549/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com