关于java读取远程文件时网络超时判断
·
今天远程FTP突然挂掉了,导致读取FTP的远程文件的程序僵死在线程了。检查发现是代码没有判断超时异常判断。现已修改,如下。
/**
* 将远程文件临时写进本地
* @param ftpUrl
* @param outputPath
*/
public static boolean writeFtpFile2Local(String ftpUrl, String outputPath) {
System.out.println("开始写文件到本地");
URLConnection con=null;
FileOutputStream fs =null;
try {
// 连接指定的网络资源,获取网络输入流
URL u=new URL(ftpUrl);
int bytesum = 0;
int byteread = 0;
con=u.openConnection();
System.setProperty("sun.net.client.defaultConnectTimeout", "60000");//jdk1.4换成这个,连接超时
System.setProperty("sun.net.client.defaultReadTimeout", "60000"); //jdk1.4换成这个,读操作超时
con.connect();
InputStream inStream = con.getInputStream();
fs= new FileOutputStream(outputPath);
byte[] buffer = new byte[1444];
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread;
fs.write(buffer, 0, byteread);
}
return true;
} catch (Exception e) {
System.out.println("读取远程文件到本地失败!请与系统管理员联系!"+ftpUrl);
e.printStackTrace();
return false;
}finally{
try {
if(fs!=null){
fs.close();
fs=null;
}
if(con!=null){
con=null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐



所有评论(0)