How to convert byte size into human-readable format in Java? Like 1024 should become '1 Kb' and 1024*1024 should become '1 Mb'.
I am kind of sick of writing this utility method for each project. Are there any static methods in Apache Commons for this?
How to convert byte size into human-readable format in Java? Like 1024 should become '1 Kb' and 1024*1024 should become '1 Mb'. I am kind of sick of writing this utility method for each project. This book is designed to present the techniques to solve problems like 7521645 x 9999999 in simpler language for School students, teachers, and professionals and a must for those appearing for competitive exams like UPSC, MBA, MCA, GMAT, GRE, CSAT, etc.
AZ_Here is my go at it (no loops and handles both SI units and binary units):
Example output:
The country doesn’t have many home-grown or domestic firms that are engaged in software programming or development. Dubai jobs salary. Abu Dhabi and Dubai are the principal software hubs of UAE with Sharjah having a smattering of companies. Software establishments from all over the world are attracted to UAE’s free economic zones as the country offers numerous incentives for doing business.
Related article: Java: Formatting byte size to human readable format
aioobeaioobeFileUtils.byteCountToDisplaySize(long size)
would work if your project can depend on org.apache.commons.io
.
Use Android builtin Class
For Android there is a class Formatter. Just one like of code and you are done.
It is Like formatFileSize()
, but trying to generate shorter numbers (showing fewer decimals).
Formats a content size to be in the form of bytes, kilobytes, megabytes, etc.
AZ_AZ_We can completely avoid using the slow Math.pow()
and Math.log()
methods without sacrificing simplicity since the factor between the units (e.g. B, KB, MB etc.) is 1024 which is 2^10. The Long
class has a handy numberOfLeadingZeros()
method which we can use to tell which unit the size value falls in.
Key point: Size units have a distance of 10 bits (1024=2^10) meaning the position of the highest 1 bit - or in other words the number of leading zeros - differ by 10 (Bytes=KB*1024, KB=MB*1024 etc.).
Correlation between number of leading zeros and size unit:
The final code:
iczaiczaI asked the same Question recently:
While there is no out-of-the-box answer, I can live with the solution:
Test code:
Output (on my German Locale):
Edit: I have opened an Issue requesting this functionality for Google Guava. Perhaps someone would care to support it.
This is a modified version of aioobe's answer.
Changes:
Locale
parameter, because some languages use .
and others ,
as decimal point.If you use Android, you can simply use Formatter.formatFileSize() .
Alternativey, here's a solution based on this popular post :
Byte Units allows you to do it like this:
I have written another library called storage-units that allows you to do it like this:
In case you want to force a certain unit, do this:
There is now one library available that contains unit formatting. I added it to the triava library, as the only other existing library seems to be one for Android.
It can format numbers with arbitrary precision, in 3 different systems (SI, IEC, JEDEC) and various output options. Here are some code examples from the triava unit tests:
Printing exact kilo, mega values (here with W = Watt):
You can pass a DecimalFormat to customize the output:
For arbitrary operations on kilo or mega values, you can split them into components:
Christian EskenChristian EskenI know it's too late to update this post! but I had some fun with this:
Create an interface:
Create StorageUnits class:
Call it:
Output:
Just add more file units (if any missing), and you will see unit size upto that unit (if your file has that much length) System.out.println('File size in proper format: ' + bytes + ' ' + fileSizeUnits[index]); sizeToReturn = String.valueOf(bytes) + ' ' + fileSizeUnits[index]; return sizeToReturn; }
Vishwajit R. ShindeVishwajit R. ShindeHere's the C# .net equivalent for Java correct consensus answer above.(there's another below which have shorter codes)
Technically speaking, if we stick to SI units, this routine works for any regular use of numbers. There are many other good answers from experts. Suppose you are doing databinding of numbers on gridviews, its worth to check out performance optimized routines from them.
PS: Posted because this question/answer came up on top on google search while I am doing C# project.
In the off-chance it saves someone a bit of time, or maybe just for a bit of fun, here's a Go version. For simplicity, I've only included the binary output case.
Rick-777Rick-777Have you tried JSR 363? Its unit extension modules like Unicode CLDR (in GitHub: uom-systems) do all that for you.
You can use MetricPrefix
included in every implementation or BinaryPrefix
(comparable to some of the examples above) and if you e.g. live and work in India or a nearby country, IndianPrefix
(also in the common module of uom-systems) allows you to use and format 'Crore Bytes' or 'Lakh Bytes', too.
Use the following function to get exact information, Generated by taking the base of ATM_CashWithdrawl
concept.
I have just modified the code of facebookarchive-StringUtils
to get the below format. Same format you will get when you use apache.hadoop-StringUtils
Example usage of the above methods:
Bytes to get above format
In order to display time in human readable format use this function millisToShortDHMS(long duration)
.