- 通过网络资源地址(http://xxx.xxx),获取该资源大小(带单位)方法如下:
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);
if (fileSize != -1) {
System.out.println("文件大小为:" + fileUnitConversion(fileSize));
} else {
System.out.println("Failed to get file size.");
}
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
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;
}
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服务器中的文件,不是本地路径文件)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/c67746e9c8455e04bcded5ef337aac89.png)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/d7325a052e594301c36285fbde6c9350.png)