该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
代码如下!
/**
* 下载文件
*/
public static void downloadHttpFile(String sURL,String folder, String sFilePath){
try {
int nStartPos = 0;
int nRead = 0;
URL url = new URL(sURL);
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setRequestMethod("HEAD");
long nEndPos = getFileSize(sURL);
RandomAccessFile oSavedFile = new RandomAccessFile(folder+sFilePath, "rw");
httpConnection.setRequestProperty("User-Agent", "Internet Explorer");
String sProperty = "bytes=" + nStartPos + "-";
httpConnection.setRequestProperty("RANGE", sProperty);
InputStream input = httpConnection.getInputStream();
byte[] b = new byte[4*1024];
while ((nRead = input.read(b, 0, 1024)) > 0 && nStartPos < nEndPos ) {//((length = in.read(b, offset, 1024)) != -1)
oSavedFile.write(b, 0, nRead);
nStartPos += nRead;
}
oSavedFile.close();
httpConnection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取文件大小
* @param sURL
* @return
*/
public static long getFileSize(String sURL) {
int nFileLength = -1;
try {
String newUrl1 = sURL.substring(0,sURL.lastIndexOf("/")+1);
String newUrl2 = sURL.substring(sURL.lastIndexOf("/")+1);
String newurl = newUrl1 + URLEncoder.encode(newUrl2, "UTF-8");
URL url = new URL(newurl);
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setRequestProperty("User-Agent", "Internet Explorer");
httpConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt;NetFox)");
long connSize = httpConnection.getContentLength();
long responseCode = httpConnection.getResponseCode();
httpConnection.getInputStream();
if (responseCode >= 400) {
System.err.println("Error Code : " + responseCode);
return -2; // -2 represent access is error
}
String sHeader;
for (int i = 1;; i++) {
sHeader = httpConnection.getHeaderFieldKey(i);
if (sHeader != null) {
if (sHeader.equals("Content-Length")) {
nFileLength = Integer.parseInt(httpConnection.getHeaderField(sHeader));
break;
}
} else
break;
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
//System.out.println(nFileLength);
return nFileLength;
}
下载下来的文件受损。我感觉问题是获取文件长度的问题,测试了无数把,每次获取的文件长度都是5KB,但是我右键保存到本地文件大小为28KB。想问问有没有大神指导指导如何解决,java获取长度的方法除了 HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(); httpConnection.getContentLength();这个方法和我上面那个getFileSize();方法还有别的什么方法吗。