Java File Size Readable Format FormatFileSize(String filesize)

Here you can find the source of FormatFileSize(String filesize)

Description

Make file size format

License

Apache License

Parameter

Parameter Description
filesize ex) "1234567"<br>

Return

result ex) "1,234,567"

Declaration

public static String FormatFileSize(String filesize) 

Method Source Code

//package com.java2s;
/**//from   w w  w. j av  a 2s  . co  m
 * Copyright 2014 tgrape Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

public class Main {
    /**
    * Make file size format
    * <br>
    * @param filesize ex) "1234567"<br>
    * @return result  ex) "1,234,567"
    */
    public static String FormatFileSize(String filesize) {
        int len = 0;
        int mok = 0;
        int mod = 0;
        String result = "";
        String reverseResult = "";
        String stringMok = "";
        String reverseMok = "";
        len = filesize.length();
        if (len < 4)
            return "1";
        mok = Integer.parseInt(filesize) / 1024;
        mod = Integer.parseInt(filesize) % 1024;
        if (Integer.parseInt(String.valueOf(mod).substring(0, 1)) >= 5)
            mok++;
        stringMok = String.valueOf(mok);
        reverseMok = reverse(stringMok);
        for (int i = 0; i < reverseMok.length(); i++) {
            reverseResult = reverseResult + reverseMok.charAt(i);
            if ((i + 1) % 3 == 0) {
                if (i == reverseMok.length() - 1)
                    continue;
                reverseResult = reverseResult + ",";
            }
        }
        result = reverse(reverseResult);
        return result;
    }

    /**
    * relation function to formatFileSize
    * @param String
    * @return String
    */
    private static String reverse(String str) {
        int i, len;
        len = str.length();
        String result = "";
        for (i = (len - 1); i >= 0; i--)
            result = result + str.charAt(i);
        return result;
    }
}

Related

  1. formatFileSize(long fileSize)
  2. formatFileSize(long fileSizeLong)
  3. formatFileSize(long size)
  4. formatFileSize(long size)
  5. formatFileSize(long size, String format)
  6. formatFilesize(String filesize, int decimalPlaces)
  7. formatFileStats(final String label, final long fileCount, final Object rawSize)
  8. formatGroup(String str, int groupSize, int lineBreak)
  9. formatIndex(int index, int totalSize)