Java URL Download nio downloadImage(String src, Path saveFolder)

Here you can find the source of downloadImage(String src, Path saveFolder)

Description

download Image

License

Apache License

Declaration

public static Path downloadImage(String src, Path saveFolder) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;

public class Main {
    public static Path downloadImage(String src, Path saveFolder) throws IOException {
        Path saveFilePath = srcImageToSavePath(src, saveFolder);

        // Open a URL Stream.
        URL url = new URL(src);
        try (InputStream in = url.openStream(); OutputStream out = Files.newOutputStream(saveFilePath)) {
            for (int b; (b = in.read()) != -1;) {
                out.write(b);/*from  w  ww.  ja v  a  2 s . co m*/
            }
        }

        return saveFilePath;
    }

    public static Path srcImageToSavePath(String src, Path saveFolder) {
        // Extract the name of the image from the src attribute.
        int indexName = src.lastIndexOf("/");

        if (indexName == src.length()) {
            src = src.substring(1, indexName + 1);
        }

        indexName = src.lastIndexOf("/") + 1;
        String name = src.substring(indexName, src.length());

        return saveFolder.resolve(name);
    }
}

Related

  1. downloadFileNIO(FileChannel fileChannel, SocketChannel socketChannel)
  2. downloadFileToDirectory(String url, File destination)
  3. downloadFirstLineFromInternetQuietly(URL url)
  4. downloadFromHttpUrl(String destPkgUrl, FileOutputStream outputStream)
  5. downloadFromInternet(URL url, File downloadTo)
  6. downloadToFile(String filename, String urlString)
  7. downloadToFile(URL url, File file)
  8. downloadToString(String url)
  9. downloadUrl(String urlstring, File file)