java判断远程文件是否存在(跨服务器)

1、使用getInputStream()

boolean isExist = false;
try{
	URL url = new URL(urlStr);// 注:urlStr中需将空格替换为%20,否则报505
	URLConnection conn = url.openConnection();
	conn.getInputStream();
	isExist  = true;
}catch(Exception e){
	// 获取失败
	isExist = false;
}

2、使用getResponseCode()

boolean isExist = false;
try{
	URL url = new URL(urlStr);// 注:urlStr中需将空格替换为%20,否则报505
	HttpURLConnection conn = (HttpURLConnection ) url.openConnection();
	int state = conn.getResponseCode();
    if(state == 200){
	    isExist  = true;
    }else{
	    isExist  = false
    }
}catch(Exception e){
	isExist = false;
}

 

你可能感兴趣的:(问题及解决方案)