Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

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

import java.io.File;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class Main {
    public static File downloadFile(String urlstr, File saveFile) {
        try {
            URL url = new URL(urlstr);// cause speed low.
            URLConnection con = url.openConnection();
            con.setDoInput(true);
            con.connect();
            InputStream ins = con.getInputStream();
            final int bufsize = 102400;

            byte[] buffer = new byte[bufsize];
            int len = -1;
            FileOutputStream bos = new FileOutputStream(saveFile);
            while ((len = ins.read(buffer)) != -1) {
                bos.write(buffer, 0, len);

            }
            ins.close();
            bos.close();
            return saveFile;
        } catch (Error e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}