提高Java中的图像下载性能

时间:2017-03-18 13:24:42

标签: java

我有几个文件的网址,我想下载一些图片,但我的代码似乎需要很长时间。下载100mb需要4分半钟。我的IPS让我从20mb / s的速度下载,所以我觉得它很慢。 这是我的代码,我可以改进什么?

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Scanner;

import javax.imageio.ImageIO;

public class Downloader {
static File file;
Scanner scanner;
static ArrayList<URL> links;

public Downloader(String filesPath)
{
    file = new File(filesPath);
    links = new ArrayList<URL>();

}


public static void main(String[] args) throws IOException {
    Downloader downloader = new Downloader("links");
    downloader.read(file);
    downloader.download(links);
}

public void read(File files) throws FileNotFoundException, MalformedURLException
{
    String line;
    for(File file:files.listFiles())
    {
        scanner = new Scanner(file);
        while(scanner.hasNextLine())
        {
            line = scanner.nextLine();
            if(line.matches(".*jpg")||line.matches(".*png"))
            {
                URL url = new URL(line);
                links.add(url);
            }
        }
    }


}
public void download(ArrayList<URL> links) throws IOException
{
    long startTime = System.currentTimeMillis();
    int i =0;
    ArrayList<URL> tempLinks = new ArrayList<URL>(links);
    for(URL url: tempLinks){
        URLConnection myURLConnection = url.openConnection();
        myURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0");
        myURLConnection.connect();
        BufferedImage img = ImageIO.read(myURLConnection.getInputStream());

        String[] parts = url.toString().split("/cards/|\\.");
        System.out.println(parts[2]);


        if(url.toString().matches(".*jpg")){
        File file = new File("downloaded\\"+parts[2]+".jpg");
        ImageIO.write(img, "jpg", file);
        }else{
            File file = new File("downloaded\\"+parts[2]+".png");
            ImageIO.write(img, "png", file);
        }

        i++;
    }

    long endTime = System.currentTimeMillis();
    System.out.println(endTime-startTime + " ms");
}

}

编辑:

URL url = new URL(imageUrl);
InputStream is = url.openStream();
OutputStream os = new FileOutputStream(destinationFile);

byte[] b = new byte[2048];
int length;

while ((length = is.read(b)) != -1) {
    os.write(b, 0, length);
}

is.close();
os.close();

}

0 个答案:

没有答案