Подтвердить что ты не робот

Как получить размер файла в mb?

У меня есть файл на сервере, и это zip файл. Как проверить размер файла больше 27 МБ?

File file = new File("U:\intranet_root\intranet\R1112B2.zip");
if (file > 27) {
   //do something
}
4b9b3361

Ответ 1

Используйте метод 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) {
  ...
}

Вы можете объединить преобразование в один шаг, но я попытался полностью проиллюстрировать этот процесс.

Ответ 2

Попробуйте выполнить следующий код:

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);

Ответ 3

Пример:

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 "";
}

Ответ 4

file.length() вернет вам длину в байтах, тогда вы разделите ее на 1048576, и теперь у вас есть мегабайты!

Ответ 6

Вы можете получить длину файла с File # length(), которая вернет значение в байтах, поэтому вам нужно разделить это 1024 * 1024, чтобы получить его значение в мб.

Ответ 7

Начиная с 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");
}

Ответ 9

Вы можете использовать подстроку, чтобы получить 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);
        }
    }