java how to show user friendly formatted output re

2019-06-14 11:02发布

问题:

Want to show nicely formatted output regarding bandwidth speed during download

I have this calculation below thanks to @Tomasz Nurkiewicz, and it show
mega*bytes* per second when i download a file.

long start = System.nanoTime();
long totalRead = 0;
final double NANOS_PER_SECOND = 1000000000.0;
final double BYTES_PER_MIB = 1024 * 1024;

    while ((val = bis.read(buffer, 0, 1024)) > 0) {
        //...
        totalRead += val;
        double speed = NANOS_PER_SECOND / BYTES_PER_MIB * totalRead / (System.nanoTime() - start + 1)
    }

Would like it to be like this. I get mega*bytes* per second from the calculation and from that i enter a if statement to select on KByte/s, MBit/s (not sure) or just like a normal FTP client show speed.

if( KByte/s something) {
   System.out.print(your current speed xx KB/s);
}else if(MByte/s something){
   System.out.print(your current speed xx MB/s);
}

My problem is what do i put in the if statement?.

hope you understand what i try to do

回答1:

There is a FileUtils.byteCountToDisplaySize() method in Apache Commons IO:

System.out.println(
  "your current speed is " + FileUtils.byteCountToDisplaySize(12345) + "/s"
)

// your current speed is 12 KB/s

Also see (possible duplicates):

  • How to convert byte size into human readable format in java?
  • Format file size as MB, GB etc


回答2:

I really don't understand exactly what you want it is confusing that you have mega**bytes per second in your switch.

As you seem to be aware a switch statement needs to have either an enum or an int - and that you current number is neither.

If you want to automatically move from Kbit/s to Mbit/s as the number gets larger then I think you want to use an if statement with a threshold.

If you want to take a setting that the user sets as a preference then you just need to pass that setting (either an enum or an int) into this function so that it can process the answer in the required format.

If you want to do neither of these things then I find your question a little confusing.