How to download and save a file from Internet using Java?

前端 未结 21 2897
情深已故
情深已故 2020-11-21 05:06

There is an online file (such as http://www.example.com/information.asp) I need to grab and save to a directory. I know there are several methods for grabbing a

21条回答
  •  鱼传尺愫
    2020-11-21 05:56

    import java.io.*;
    import java.net.*;
    
    public class filedown {
        public static void download(String address, String localFileName) {
            OutputStream out = null;
            URLConnection conn = null;
            InputStream in = null;
    
            try {
                URL url = new URL(address);
                out = new BufferedOutputStream(new FileOutputStream(localFileName));
                conn = url.openConnection();
                in = conn.getInputStream();
                byte[] buffer = new byte[1024];
    
                int numRead;
                long numWritten = 0;
    
                while ((numRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, numRead);
                    numWritten += numRead;
                }
    
                System.out.println(localFileName + "\t" + numWritten);
            } 
            catch (Exception exception) { 
                exception.printStackTrace();
            } 
            finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                    if (out != null) {
                        out.close();
                    }
                } 
                catch (IOException ioe) {
                }
            }
        }
    
        public static void download(String address) {
            int lastSlashIndex = address.lastIndexOf('/');
            if (lastSlashIndex >= 0 &&
            lastSlashIndex < address.length() - 1) {
                download(address, (new URL(address)).getFile());
            } 
            else {
                System.err.println("Could not figure out local file name for "+address);
            }
        }
    
        public static void main(String[] args) {
            for (int i = 0; i < args.length; i++) {
                download(args[i]);
            }
        }
    }
    

提交回复
热议问题