Java File Size Readable Format formatSize(String strSize)

Here you can find the source of formatSize(String strSize)

Description

Formats the given size for display in a directory listing

License

Apache License

Parameter

Parameter Description
strSize The content size

Return

The formatted size

Declaration

public static String formatSize(String strSize) 

Method Source Code

//package com.java2s;
/*//from   w  w  w.  j  a  va 2s.co m
 * Copyright 2002-2007 the original author or authors.
 *
 * 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 {
    /**
     * Formats the given size for display in a directory listing
     * 
     * @param strSize The content size
     * @return The formatted size
     */
    public static String formatSize(String strSize) {
        String strFormattedSize = strSize;

        int length = strSize.length();
        if (length < 4) {
            strFormattedSize = strSize + "B";
        } else if (length >= 4 && length < 7) {
            String strLeft = strSize.substring(0, length - 3);
            String strRight = strSize.substring(length - 3, length - 2);

            StringBuilder buffer = new StringBuilder(strLeft);
            if (!strRight.equals('0')) {
                buffer.append('.');
                buffer.append(strRight);
            }
            buffer.append(" K");

            strFormattedSize = buffer.toString();
        } else {
            String strLeft = strSize.substring(0, length - 6);
            String strRight = strSize.substring(length - 6, length - 5);

            StringBuilder buffer = new StringBuilder(strLeft);
            if (!strRight.equals('0')) {
                buffer.append('.');
                buffer.append(strRight);
            }
            buffer.append(" M");

            strFormattedSize = buffer.toString();
        }

        return strFormattedSize;
    }
}

Related

  1. formatSize(long size)
  2. FormatSize(long size)
  3. formatSize(Long size)
  4. formatSize(long size)
  5. formatSize(long v)
  6. formatSize(StringBuilder builder, Long size)
  7. formatSizeInBytes(int size)
  8. formatSpaceUsage(long size)
  9. formatToolBarDisplay(String text, int size)