- 通過網(wǎng)絡(luò)資源地址(http://xxx.xxx),獲取該資源大?。◣挝唬┓椒ㄈ缦拢?/li>
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;
public class GetFileSize {
public static void main(String[] args) {
String fileUrl = "http://xxx.xx.xx.xx:xxxx/uploadfiles/2.mp4"; //文件路徑
try {
long fileSize = getFileSize(fileUrl); //調(diào)用獲取文件大小方法
if (fileSize != -1) {
System.out.println("文件大小為:" + fileUnitConversion(fileSize)); //調(diào)用文件大小單位轉(zhuǎn)換方法
} else {
System.out.println("Failed to get file size.");
}
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
/**
* 獲取文件大小方法
*
* @param fileUrl 文件路徑
* @return
* @throws IOException
*/
public static long getFileSize(String fileUrl) throws IOException {
URL url = new URL(fileUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("HEAD");
connection.connect();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
String contentLength = connection.getHeaderField("Content-Length");
if (contentLength != null) {
return Long.parseLong(contentLength);
}
}
return -1; // 返回-1表示獲取文件大小失敗
}
/**
* 文件大小單位轉(zhuǎn)換方法: B/KB/MB/GB
*
* @param contentLength 文件大小
* @return
*/
public static String fileUnitConversion(Long contentLength) {
DecimalFormat df = new DecimalFormat("#.00");
String fileSizeString;
long fileSize = contentLength;
if (fileSize < 1024) {
fileSizeString = df.format((double) fileSize) + "B";
} else if (fileSize < 1048576) {
fileSizeString = df.format((double) fileSize / 1024) + "KB";
} else if (fileSize < 1073741824) {
fileSizeString = df.format((double) fileSize / 1048576) + "MB";
} else {
fileSizeString = df.format((double) fileSize / 1073741824) + "GB";
}
return fileSizeString;
}
}
- 文件大?。ㄎ疫@里是本地Tomcat服務(wù)器中的文件,不是本地路徑文件)
文章來源:http://www.zghlxwxcb.cn/news/detail-840393.html
- 讀取到的文件大小
文章來源地址http://www.zghlxwxcb.cn/news/detail-840393.html
到了這里,關(guān)于Java獲取HTTP網(wǎng)絡(luò)資源文件大?。◣挝唬┑奈恼戮徒榻B完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!