У меня есть файл на сервере, и это zip файл. Как проверить размер файла больше 27 МБ?
File file = new File("U:\intranet_root\intranet\R1112B2.zip");
if (file > 27) {
//do something
}
У меня есть файл на сервере, и это zip файл. Как проверить размер файла больше 27 МБ?
File file = new File("U:\intranet_root\intranet\R1112B2.zip");
if (file > 27) {
//do something
}
Используйте метод 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) {
...
}
Вы можете объединить преобразование в один шаг, но я попытался полностью проиллюстрировать этот процесс.
Попробуйте выполнить следующий код:
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);
Пример:
public static String getStringSizeLengthFile(long size) {
DecimalFormat df = new DecimalFormat("0.00");
float sizeKb = 1024.0f;
float sizeMo = sizeKb * sizeKb;
float sizeGo = sizeMo * sizeKb;
float sizeTerra = sizeGo * sizeKb;
if(size < sizeMo)
return df.format(size / sizeKb)+ " Kb";
else if(size < sizeGo)
return df.format(size / sizeMo) + " Mo";
else if(size < sizeTerra)
return df.format(size / sizeGo) + " Go";
return "";
}
file.length() вернет вам длину в байтах, тогда вы разделите ее на 1048576, и теперь у вас есть мегабайты!
Проще всего использовать FileUtils из Apache commons-io. (https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FileUtils.html)
Возвращает размер читаемого файла от байтов до Exabytes, округляя до границы.
File fileObj = new File(filePathString);
String fileSizeReadable = FileUtils.byteCountToDisplaySize(fileObj.length());
// output will be like 56 MB
Вы можете получить длину файла с File # length(), которая вернет значение в байтах, поэтому вам нужно разделить это 1024 * 1024, чтобы получить его значение в мб.
Начиная с Java 7 вы можете использовать java.nio.file.Files.size(Path p)
.
Path path = Paths.get("C:\\1.txt");
long expectedSizeInMB = 27;
long expectedSizeInBytes = 1024 * 1024 * expectedSizeInMB;
long sizeInBytes = -1;
try {
sizeInBytes = Files.size(path);
} catch (IOException e) {
System.err.println("Cannot get the size - " + e);
return;
}
if (sizeInBytes > expectedSizeInBytes) {
System.out.println("Bigger than " + expectedSizeInMB + " MB");
} else {
System.out.println("Not bigger than " + expectedSizeInMB + " MB");
}
public static long sizeOf(File file)
Дополнительная информация о API: http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html
Вы можете использовать подстроку, чтобы получить portio строки String, которая равна 1 мб:
public static void main(String[] args) {
// Get length of String in bytes
String string = "long string";
long sizeInBytes = string.getBytes().length;
int oneMb=1024*1024;
if (sizeInBytes>oneMb) {
String string1Mb=string.substring(0, oneMb);
}
}