Format file length in string in Java

Description

The following code shows how to format file length in string.

Example


//from ww w  .j  a v  a  2s . c o m
public class Main {
  public static void main(String[] argv){
    System.out.println(format(123123123L));
  }
  public static final String format(long l) {

    String s = String.valueOf(l);
    int digits = 0;
    while (s.length() > 3) {
      s = s.substring(0, s.length() - 3);
      digits++;
    }
    StringBuffer buffer = new StringBuffer();
    buffer.append(s);
    if ((s.length() == 1) && (String.valueOf(l).length() >= 3)) {
      buffer.append(".");
      buffer.append(String.valueOf(l).substring(1, 3));
    } else if ((s.length() == 2) && (String.valueOf(l).length() >= 3)) {
      buffer.append(".");
      buffer.append(String.valueOf(l).substring(2, 3));
    }
    if (digits == 0) {
      buffer.append(" B");
    } else if (digits == 1) {
      buffer.append(" KB");
    } else if (digits == 2) {
      buffer.append(" MB");
    } else if (digits == 3) {
      buffer.append(" GB");
    } else if (digits == 4) {
      buffer.append(" TB");
    }
    return buffer.toString();

  }

}

The code above generates the following result.





















Home »
  Java Tutorial »
    I/O »




Binary File
Byte Array
CharSet
Checksum
Console
Create Copy Move Delete
Directory
Drive
Encode Decode
File Attribute
File Lock
File System
GZIP
Jar File
NIO Buffer
Path
Scanner
StreamTokenizer
Temporary File
Text File
Zip