简体   繁体   English

物理传输速度Java IO

[英]Physical transfer speed Java IO

Is there a way to see the transfer speed (MB/s) while copying files? 复制文件时是否有办法查看传输速度(MB / s)? This is not for network sockets but for hdd to hdd for example. 例如,这不是用于网络套接字,而是用于从HDD到HDD。 i copy the files content in bytes. 我以字节为单位复制文件内容。 Code for copying files: platform is windows 复制文件的代码:平台是Windows

while ((length = in.read(buffer)) > 0) {
    out.write(buffer, 0, length);
    totalBytesCopied += length;
    int totalKilos = (int) totalBytesCopied / 1024;
    int totalMegas = totalKilos / 1024;
}

A example of how this can be done? 如何做到这一点的一个例子? Kind Regards 亲切的问候

A kind of. 一种。 First you can do it at application level. 首先,您可以在应用程序级别执行此操作。 Your code that copies file should look like: 复制文件的代码应如下所示:

    byte[] buffer = new byte[BUFFER_SIZE];
    int n = 0;
    while (-1 != (n = input.read(buffer))) {
        output.write(buffer, 0, n);
    }

So, modify it as following: 因此,将其修改如下:

    byte[] buffer = new byte[BUFFER_SIZE];
    int n = 0;
    long before = System.currentTimeMillis();
    while (-1 != (n = input.read(buffer))) {
        output.write(buffer, 0, n);
        long after = System.currentTimeMillis();
        double speed = n / (after - before) * 1000; // speed in byte per second 
        before = System.currentTimeMillis();
    }

You can do better. 你可以做得更好。 Implement SpeedMeasurementOutputStream that wraps any output stream and performs similar logic into its write() method. 实现SpeedMeasurementOutputStream ,它包装所有输出流,并在其write()方法中执行类似的逻辑。 Then wrap FileOutputStream using this stream and get the speed while copying. 然后使用此流包装FileOutputStream并在复制时获得速度。 This approach is better because this way you can measure speed of any stream. 这种方法更好,因为您可以通过这种方法测量任何流的速度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM