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

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

    If you are behind a proxy, you can set the proxies in java program as below:

            Properties systemSettings = System.getProperties();
            systemSettings.put("proxySet", "true");
            systemSettings.put("https.proxyHost", "https proxy of your org");
            systemSettings.put("https.proxyPort", "8080");
    

    If you are not behind a proxy, don't include the lines above in your code. Full working code to download a file when you are behind a proxy.

    public static void main(String[] args) throws IOException {
            String url="https://raw.githubusercontent.com/bpjoshi/fxservice/master/src/test/java/com/bpjoshi/fxservice/api/TradeControllerTest.java";
            OutputStream outStream=null;
            URLConnection connection=null;
            InputStream is=null;
            File targetFile=null;
            URL server=null;
            //Setting up proxies
            Properties systemSettings = System.getProperties();
                systemSettings.put("proxySet", "true");
                systemSettings.put("https.proxyHost", "https proxy of my organisation");
                systemSettings.put("https.proxyPort", "8080");
                //The same way we could also set proxy for http
                System.setProperty("java.net.useSystemProxies", "true");
                //code to fetch file
            try {
                server=new URL(url);
                connection = server.openConnection();
                is = connection.getInputStream();
                byte[] buffer = new byte[is.available()];
                is.read(buffer);
    
                    targetFile = new File("src/main/resources/targetFile.java");
                    outStream = new FileOutputStream(targetFile);
                    outStream.write(buffer);
            } catch (MalformedURLException e) {
                System.out.println("THE URL IS NOT CORRECT ");
                e.printStackTrace();
            } catch (IOException e) {
                System.out.println("Io exception");
                e.printStackTrace();
            }
            finally{
                if(outStream!=null) outStream.close();
            }
        }
    

提交回复
热议问题