使用Eclipse测量下载速度

时间:2015-06-24 21:20:46

标签: java eclipse

几天前,我建议使用此代码来测量下载速度。但是我不太明白URL和&输出文件以使代码生效。有人可以向我解释一下吗?我对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作为网址。然而,无论我是否正在下载文件,它只返回3KB​​到300KB之间的值......

1 个答案:

答案 0 :(得分:1)

网址 - >您要下载的网页

输出文件 - >它将被下载的地方。根据代码,它将在您的项目文件夹中创建。不知道为什么他们的名字像.jpg。你可以把它命名为任何东西..打开那个文件,你将会下载许多html。

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