ファイルサイズByte、KB、MB、GB、TB単位自動変換を取得します。
ファイルサイズByte、KB、MB、GB、TB単位自動変換を取得します。
これはByteを直接取得するものです。
これはByteを直接取得するものです。
/**
* (Byte)
* @param file
* @return null
*/
public static Long getByteSize(File file) {
if (file.exists() && file.isFile()) {
return file.length();
}
return null;
}
これはタイトルが言っている場合、ファイルサイズが作成された最大単位が単位であると自動的に判断されます。サイズは小数点以下3桁、四捨五入の文字列です。/**
* ( )
* :1024Byte Byte
* 1KB
* 3
* @param file
* @return null
*/
public static String getSize(File file) {
long size = getByteSize(file);
double s = (double) size;
String unit;
if (size != -1L) {
int l;
if (size < 1024L) {
l = 0;
} else if (size < 1024L * 1024L) {
l = 1;
s = (double) size / 1024L;
} else {
for (l = 2; size >= 1024L * 1024L; l++) {
size = size / 1024L;
if ((size / 1024L) < 1024L) {
s = (double) size / 1024L;
break;
}
}
}
switch (l) {
case 0:
unit = "Byte";
break;
case 1:
unit = "KB";
break;
case 2:
unit = "MB";
break;
case 3:
unit = "GB";
break;
case 4:
//
unit = "TB";
break;
default:
//ER
unit = "ER";
}
String format = String.format("%.3f", s);
return format + unit;
}
return null;
}