LoginSignup
5
2

More than 5 years have passed since last update.

ファイルサイズをヒューマンリーダブルな形に変換する

Last updated at Posted at 2017-02-06

 大きなファイルの操作で,ユーザに進捗を見せる時,byteだけ見せるとツライですよね.
 百分率で表示するのもいいですが,これだと絶対的なファイルの大きさがわからない不安もあります.

 なので,ユーザに見せるときは以下のようにヒューマンリーダブルな形変換してあげると良いわけですが

  • 10240(bytes) → 10KB
  • 16684887565184(bytes) → 15.17TB

 難しくないロジックのせいか,Java標準にもApache commonsあたりにも見当たらないんですが,フォーマットに特にこだわらなければAndroidSdkで機能提供されていますので,利用すると良いと思います.

import android.text.format.Formatter;

Formatter.formatFileSize(context, 1024); // -> "1.00KB"
Formatter.formatFileSize(context, 900); // -> "900B"
Formatter.formatFileSize(context, 1024 * 1024); // -> "1.00MB"

Contextを要求されるのは, KBなどの文字列をリソースから読んでいるためですね.

5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2