Here you can find the source of saveImageAsFile(String imageUrl, String destinationFile, boolean overwrite)
Parameter | Description |
---|---|
imageUrl | a parameter |
destinationFile | a parameter |
overwrite | a parameter |
Parameter | Description |
---|---|
IOException | an exception |
public static long saveImageAsFile(String imageUrl, String destinationFile, boolean overwrite)
//package com.java2s; /*// w w w . j a v a 2 s .c o m * Copyright 2013 Midhun Harikumar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; public class Main { private static final int BUFFER_SIZE = 4096; /** * Save an image url to the disk * * @param imageUrl * @param destinationFile * @param overwrite * @throws IOException */ public static long saveImageAsFile(String imageUrl, String destinationFile, boolean overwrite) { URL url = null; long fileSize = 0; InputStream is = null; OutputStream os = null; try { if (overwrite == false) { // If overwrite is false, check if the file exists File file = new File(destinationFile); if (file.exists()) { // Short circuit the file saving logic throw new Exception("Skipping save as file already exists"); } } // Open the image URL stream and download / read the image data url = new URL(imageUrl); is = url.openStream(); os = new FileOutputStream(destinationFile); // At a time, BUFFER_SIZE amount of data will be read from the stream byte[] b = new byte[BUFFER_SIZE]; int length; while ((length = is.read(b)) != -1) { fileSize += length; os.write(b, 0, length); } } catch (IOException e) { System.err.println(e.getMessage()); } catch (Exception e) { System.err.println(e.getMessage()); } finally { try { if (is != null) is.close(); if (os != null) os.close(); } catch (IOException e) { System.err.println(e.getMessage()); return fileSize; } } return fileSize; } }