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

前端 未结 21 2895
情深已故
情深已故 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:52

    public class DownloadManager {
    
        static String urls = "[WEBSITE NAME]";
    
        public static void main(String[] args) throws IOException{
            URL url = verify(urls);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            InputStream in = null;
            String filename = url.getFile();
            filename = filename.substring(filename.lastIndexOf('/') + 1);
            FileOutputStream out = new FileOutputStream("C:\\Java2_programiranje/Network/DownloadTest1/Project/Output" + File.separator + filename);
            in = connection.getInputStream();
            int read = -1;
            byte[] buffer = new byte[4096];
            while((read = in.read(buffer)) != -1){
                out.write(buffer, 0, read);
                System.out.println("[SYSTEM/INFO]: Downloading file...");
            }
            in.close();
            out.close();
            System.out.println("[SYSTEM/INFO]: File Downloaded!");
        }
        private static URL verify(String url){
            if(!url.toLowerCase().startsWith("http://")) {
                return null;
            }
            URL verifyUrl = null;
    
            try{
                verifyUrl = new URL(url);
            }catch(Exception e){
                e.printStackTrace();
            }
            return verifyUrl;
        }
    }
    

提交回复
热议问题