Hola,
el siguiente código sirve para transformar un long (en este caso, tamaño del archivo) a un formato entendible.

Código:

Código: Seleccionar todo

public static String formatBytes(long bytes) {
        String[] Q = new String[]{"", "kb", "mb", "gb", "tb", "pb", "eb"};
        for (int i = 6; i > 0; i--) {
            double step = Math.pow(1024, i);
            if (bytes > step) {
                return String.format("%3.1f %s", bytes / step, Q[i]);
            }
        }
        return Long.toString(bytes);
    }
Ejemplo:

Código: Seleccionar todo

File archivo = new File("archivo1.exe");
        long medida = archivo.length();
        System.out.println("El tamaño del archivo1 es: "+formatBytes(medida));
        
        archivo = new File("archivo2.exe");
        medida = archivo.length();
        System.out.println("El tamaño del archivo2 es: "+formatBytes(medida));
        
        archivo = new File("archivo3.exe");
        medida = archivo.length();
        System.out.println("El tamaño del archivo3 es: "+formatBytes(medida));
Imagen:
Imagen
Responder

Volver a “Fuentes”