使用Eclipse测量下载速度



几天前,有人建议我使用此代码来测量下载速度。然而,我不太明白在URL&用于代码工作的outputfile。有人能给我解释一下吗?我对java只有非常基本的理解。提前谢谢。

public class Speed {
    @SuppressWarnings("resource")
    public double getSpeed() throws IOException{
        URL website = new URL("https://www.youtube.com/"); //The source website
        ReadableByteChannel rbc = Channels.newChannel(website.openStream());
        File outputFile = new File("output.jpg"); //The output file
        outputFile.createNewFile();
        FileOutputStream fos = new FileOutputStream(outputFile);
        long startTime = System.nanoTime(); //Measure when you start to download the file, we know that the time it takes to download a file is endTime-startTime
        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        long endTime = System.nanoTime(); //Measure when we're done downloading the file
        long fileBytes = outputFile.length();
        double downloadTimeSeconds = ((double)(endTime-startTime))/1000000000; //1 billion nanoseconds in a second
        double bytesPerSecond = ((double)fileBytes)/downloadTimeSeconds;
        return bytesPerSecond;          
    }
}

我已经用download.html作为文件输出测试了代码;http://www.thinkbroadband.com/download.html作为URL。然而,它只是返回3KB-300KB之间的值,无论我是否正在下载文件。。。

URL->您想要下载的网页

输出文件->下载位置。根据代码,它将在您的项目文件夹中创建。不知道他们为什么命名为.jpg。你可以随便命名。。打开那个文件,你会看到很多下载的html。

它返回的内容->根据变量的名称,显然根据逻辑,它是"每秒下载的字节数"

最新更新