0

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

Erik
  • 5,039
  • 10
  • 63
  • 119

2 Answers2

2

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):

Community
  • 1
  • 1
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • grate im using [Mr Ed](http://stackoverflow.com/questions/3263892/format-file-size-as-mb-gb-etc) answers from your link, thanks. Only problem is my code gives me doubles like 0.5683736337 MByte/s and i need to convert that to a long since @Mr Ed method takes a long value. Is 0.5683736337 same as 5683736337 MBytes?? – Erik Nov 17 '11 at 08:54
  • 2
    Just skip the "` / BYTES_PER_MIB`" part to haves bytes rather than MiB. – Tomasz Nurkiewicz Nov 17 '11 at 08:56
1

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.

Grouchal
  • 9,756
  • 6
  • 34
  • 46
  • updating my question, yes if statement i better i see that. But what values to if statement on? I think i might set values wrong and show Mbit when it's Kbit or something since i have problems checking the output correctness. – Erik Nov 16 '11 at 21:41