您的位置:首页 > 编程语言 > Java开发

java访问远程文件判断是否存在的问题

2017-06-28 11:42 375 查看
最近做了一个访问远程文件是否存在的程序

其中判断远程文件是否存在的内容是这样的:

import java.net.HttpURLConnection;

import java.net.URL;

import org.apache.tomcat.util.codec.binary.StringUtils;

import aachina.zhu.service.TotdcallrecordService;

import aachina.zhu.webserviceget.RedirectWeChat;

public class ToUrl2 {

TotdcallrecordService ts = new TotdcallrecordService();
RedirectWeChat rw = new RedirectWeChat();

public void toUrl() throws Exception {
// 得到url
String tourl = ts.getUrl();
//文件路径   可远程  可本地
URL url = new URL(tourl);
//URL url = new URL("http://192.168.10.206/2017HUWQ/27/WG110sdat1481/192.168.10.201!1~R!06272017_122133!Trk(02195590)!1481!WG1100!DNIS56634190!1493455851!0!R.wav");

//连接访问
HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
System.out.println("url="+url);
Long TotalSize = Long.parseLong(urlcon.getHeaderField("Content-Length"));
System.out.println("TotalSize="+TotalSize);
if (TotalSize != 1308) {
System.out.println("存在");
} else {
rw.toWeChat();
System.out.println("不存在");
}

}

}

网上看了好多,他们是这样的:

 方法一:
       URL serverUrl = new URL("http://localhost:8090/Demo/clean.sql");
HttpURLConnection urlcon = (HttpURLConnection) serverUrl.openConnection();

String message = urlcon.getHeaderField(0);
if (StringUtils.hasText(message) && message.startsWith("HTTP/1.1 404")) {
System.out.println("不存在");
}else{
System.out.println("存在"+message);
}

方法二:
URL url = new URL("http://localhost:8090/Demo/clean.sql");
HttpURLConnection urlcon2 = (HttpURLConnection) url.openConnection();
Long TotalSize=Long.parseLong(urlcon2.getHeaderField("Content-Length"));
if (TotalSize>0){
System.out.println("存在");

}else{
System.out.println("不存在");
}

可是,结果是在方法一中:

StringUtils.hasText这个方法根本找不到!!看了好多也不知道改导哪个jar包.无奈都试过了,结果还是不行


在方法二中:

无论怎么访问,他的

TotalSize的结果都是  >0  的,很揪心..

正确访问  比如这样:

Accept-Ranges:bytes
Content-Length:24956
Content-Type:audio/wav
错误路径访问:比如这样...
Content-Length:1308
<
4000
div class="header-name" style="min-width:0px;min-height:0px;color:rgb(84,84,84);display:inline-block;margin-right:.5em;font-weight:bold;vertical-align:top;white-space:pre-wrap;">Content-Type:text/html
Date:Wed, 28 Jun 2017 03:50:00 GMT
Server:Microsoft-IIS/6.0
于是.我就抖了个机灵:
路径一定不会有问题,没有文件不就是1380?于是:....

我的代码就变身了

验证过后完全没问题.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java