Java URL Copy copy_url_to_file(String url, String filename)

Here you can find the source of copy_url_to_file(String url, String filename)

Description

copurtfile

License

Apache License

Declaration

public static void copy_url_to_file(String url, String filename) throws IOException 

Method Source Code


//package com.java2s;
/*//from   w  w w. ja  v  a2s.  c om
 Copyright (C) 2012 The Stanford MobiSocial Laboratory
    
   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.*;

import java.net.URL;

public class Main {
    public static void copy_url_to_file(String url, String filename) throws IOException {
        URL u = new URL(url);
        InputStream is = u.openStream();
        copy_stream_to_file(is, filename);
    }

    public static long copy_stream_to_file(InputStream is, String filename) throws IOException {
        int bufsize = 64 * 1024;
        long nBytes = 0;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is, bufsize);
            bos = new BufferedOutputStream(new FileOutputStream(filename), bufsize);
            byte buf[] = new byte[bufsize];
            while (true) {
                int n = bis.read(buf);
                if (n <= 0)
                    break;
                bos.write(buf, 0, n);
                nBytes += n;

            }
        } finally {
            if (bis != null)
                bis.close();
            if (bos != null)
                bos.close();
        }
        return nBytes;
    }

    public static void close(Closeable resource) {
        if (resource != null) {
            try {
                resource.close();
            } catch (IOException e) {
                // Do your thing with the exception. Print it, log it or mail it.
                e.printStackTrace();
            }
        }
    }
}

Related

  1. copy(URL fromUrl, File toFile)
  2. copy(URL in, File out)
  3. copy(URL source, String destination)
  4. copyFile(URL url, String destFilePath)
  5. copyFromURL(final String query, final File target)
  6. copyRemoteFile(URL url, File localFile)
  7. copyResource(URL from, File to)