itr*_*tro 56 java url file filesize
我在服务器上有一个文件,它是一个zip文件.如何检查文件大小是否大于27 MB?
File file = new File("U:\intranet_root\intranet\R1112B2.zip");
if (file > 27) {
//do something
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*ams 136
使用类的length()方法File以字节为单位返回文件的大小.
// Get file from file name
File file = new File("U:\intranet_root\intranet\R1112B2.zip");
// Get length of file in bytes
long fileSizeInBytes = file.length();
// Convert the bytes to Kilobytes (1 KB = 1024 Bytes)
long fileSizeInKB = fileSizeInBytes / 1024;
// Convert the KB to MegaBytes (1 MB = 1024 KBytes)
long fileSizeInMB = fileSizeInKB / 1024;
if (fileSizeInMB > 27) {
...
}
Run Code Online (Sandbox Code Playgroud)
您可以将转换合并为一个步骤,但我已尝试完全说明该过程.
end*_*ian 42
请尝试以下代码:
File file = new File("infilename");
// Get the number of bytes in the file
long sizeInBytes = file.length();
//transform in MB
long sizeInMb = sizeInBytes / (1024 * 1024);
Run Code Online (Sandbox Code Playgroud)
Nic*_*las 33
示例:
public static String getStringSizeLengthFile(long size) {
DecimalFormat df = new DecimalFormat("0.00");
float sizeKb = 1024.0f;
float sizeMb = sizeKb * sizeKb;
float sizeGb = sizeMb * sizeKb;
float sizeTerra = sizeGb * sizeKb;
if(size < sizeMb)
return df.format(size / sizeKb)+ " Kb";
else if(size < sizeGb)
return df.format(size / sizeMb) + " Mb";
else if(size < sizeTerra)
return df.format(size / sizeGb) + " Gb";
return "";
}
Run Code Online (Sandbox Code Playgroud)
最简单的方法是使用Apache commons-io中的FileUtils.(https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FileUtils.html)
返回人类可读的文件大小,从Bytes到Exabytes,向下舍入到边界.
File fileObj = new File(filePathString);
String fileSizeReadable = FileUtils.byteCountToDisplaySize(fileObj.length());
// output will be like 56 MB
Run Code Online (Sandbox Code Playgroud)
file.length()将返回以字节为单位的长度,然后将其除以1048576,现在你已经有了兆字节!
| 归档时间: |
|
| 查看次数: |
113205 次 |
| 最近记录: |