如何获取以 MB(兆字节)为单位的文件大小?

新手上路,请多包涵

我在服务器上有一个 zip 文件。

如何检查文件大小是否大于 27 MB?

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

原文由 itro 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 501
2 个回答

使用 File 类的 length() 方法返回文件的大小(以字节为单位)。

 // 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) {
  ...
}

您可以将转换合并为一个步骤,但我已尝试完整说明该过程。

原文由 Marcus Adams 发布,翻译遵循 CC BY-SA 3.0 许可协议

试试下面的代码:

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

原文由 endian 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题