duminică, 29 noiembrie 2015

[OmniFaces utilities 2.0/2.4] Format the given bytes to nearest 10^n with IEC binary unit (KiB, MiB, etc)


[OmniFaces utilities] The formatBytes() function formats the given bytes to nearest 10n with IEC binary unit (KiB, MiB, etc) with rounding precision of 1 fraction. For example:
  • 1023 bytes will appear as 1023 B
  • 1024 bytes will appear as 1.0 KiB
  • 500000 bytes will appear as 488.3 KiB
  • 1048576 bytes will appear as 1.0 MiB
. The format locale will be set to the one as obtained by Faces#getLocale().

Function:

OmniFaces 2.4OmniFaces 2.0
See also: Faces#getLocale()
Usage:

Let's suppose that we have a map that contains several files names and their sizes in bytes, as below:

// in real cases, you may loop a folder to extract the files
private final Map<Long, String> fileMap
         = Collections.unmodifiableMap(new HashMap<Long, String>() {
 {
  put(13523424L, "flowers.png");
  put(2343L, "script.txt");
  put(343L, "Demo.java");
  put(4565652L, "paint.jpg");
  put(1024L, "fire.jpg");
 }
});

public Map<Long, String> getFileMap() {
 return fileMap;
}

Now, we can display a table containing these files names and sizes. The sizes are formatted via of:formatBytes():

<h:dataTable value="#{fileBean.fileMap.entrySet()}" var="file">
 <h:column>
  <f:facet name="header">File</f:facet>
  #{file.value}
 </h:column>
 <h:column>
  <f:facet name="header">Size</f:facet>
  #{of:formatBytes(file.key)}
 </h:column>
</h:dataTable>

Output:

Niciun comentariu:

Trimiteți un comentariu