문제

누군가가 Java/JSP/JSTL 페이지에서 파일 크기를 포맷하는 좋은 방법을 알고 있는지 궁금했습니다.

이를 수행하는 util 클래스가 있습니까?
나는 커먼즈를 검색했지만 아무것도 찾지 못했습니다. 맞춤 태그가 있습니까?
라이브러리가 이미 존재합니까?

이상적으로 나는 그것이처럼 행동하기를 원합니다 -시간 유닉스를 켜십시오 ls 명령

34 -> 34
795 -> 795
2646-> 2.6K
2705-> 2.7K
4096-> 4.0K
13588-> 14K
28282471-> 27m
28533748-> 28m

도움이 되었습니까?

해결책

빠른 Google 검색이 저를 반환했습니다 이것 Appache Hadoop 프로젝트에서. 거기에서 복사 : (Apache 라이센스, 버전 2.0) :

private static DecimalFormat oneDecimal = new DecimalFormat("0.0");

  /**
   * Given an integer, return a string that is in an approximate, but human 
   * readable format. 
   * It uses the bases 'k', 'm', and 'g' for 1024, 1024**2, and 1024**3.
   * @param number the number to format
   * @return a human readable form of the integer
   */
  public static String humanReadableInt(long number) {
    long absNumber = Math.abs(number);
    double result = number;
    String suffix = "";
    if (absNumber < 1024) {
      // nothing
    } else if (absNumber < 1024 * 1024) {
      result = number / 1024.0;
      suffix = "k";
    } else if (absNumber < 1024 * 1024 * 1024) {
      result = number / (1024.0 * 1024);
      suffix = "m";
    } else {
      result = number / (1024.0 * 1024 * 1024);
      suffix = "g";
    }
    return oneDecimal.format(result) + suffix;
  }

1k = 1024를 사용하지만 원하는 경우이를 조정할 수 있습니다. 또한 <1024 사례를 다른 십진법으로 처리해야합니다.

다른 팁

Commons-Io를 사용할 수 있습니다 FileUtils.byteCountToDisplaySize 행동 양식. JSTL 구현의 경우 ClassPath에 Commons-IO가있는 동안 다음 Taglib 기능을 추가 할 수 있습니다.

<function>
  <name>fileSize</name>
  <function-class>org.apache.commons.io.FileUtils</function-class>
  <function-signature>String byteCountToDisplaySize(long)</function-signature>
</function>

이제 JSP에서는 할 수 있습니다.

<%@ taglib uri="/WEB-INF/FileSizeFormatter.tld" prefix="sz"%>
Some Size: ${sz:fileSize(1024)} <!-- 1 K -->
Some Size: ${sz:fileSize(10485760)} <!-- 10 MB -->
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top