java里获取本地文件大小可以直接new File(url).length(),但是获取网络文件大小需要有点改动,代码如下,需要时自取:
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.log4j.Logger;
public class FileTest {
private static final Logger logger = Logger
.getLogger(FileTest.class);
public static void main(String[] args){
FileTest fileTest = new FileTest();
String url = "http://211.64.201.201/uploadfile/nyz.mp3";
try {
System.out.println("文件大小:"+fileTest.getFileLength(url));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 获取网络文件大小
* @param url
* @param type
* @return
* @throws IOException
*/
private int getFileLength(String url1) throws IOException{
int length=0;
URL url;
try {
url = new URL(url1);
HttpURLConnection urlcon=(HttpURLConnection)url.openConnection();
//根据响应获取文件大小
length=urlcon.getContentLength();
urlcon.disconnect();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return length;
}
}