Simple java class to download the file

情到浓时终转凉″ 提交于 2019-12-06 12:23:33

问题


I am trying to download a file using simple java class using the following code:

public class Download {  

     public static void main(String[] args) throws Exception {  

        Download d = new Download();  
        d.URLSetUp("http://www.sheldonbrown.com/web_sample1.html");  
     }  

    public String URLSetUp(String urlProp) throws Exception {  

        StringBuffer tempData = new StringBuffer();  
        String contentXML = "";  
        String line = "";  
        URL url1;  
         try {  
            url1 = new URL(urlProp);  

            URLConnection conn = url1.openConnection();  

            conn.setDoOutput(true);  
             OutputStreamWriter wr = new OutputStreamWriter(conn
                .getOutputStream());  

             BufferedReader rd = new BufferedReader(new InputStreamReader(conn
                .getInputStream()));  
              while ((line = rd.readLine()) != null) {  
                 tempData.append(line);  
             }  
             contentXML = tempData.toString();  

            wr.close();  
            rd.close();  

         } catch (MalformedURLException e) {  

             e.printStackTrace();  
         } catch (IOException e) {  

             e.printStackTrace();  
        }  
         if (contentXML != null) {  
             return contentXML;  
        } else {  

             System.out.println("Error");  
         }  
         return null;  

     }  
}  

Its giving me following error:

#  
# An unexpected error has been detected by Java Runtime Environment:  
#  
#  Internal Error (434C41535326494C453041525345520E4350500B65), pid=5156, tid=4296  
#  
# Java VM: Java HotSpot(TM) Client VM (1.6.0_03-b05 mixed mode)  
# An error report file with more information is saved as hs_err_pid5156.log  
#  
# If you would like to submit a bug report, please visit:  
#   http://java.sun.com/webapps/bugreport/crash.jsp  
#

Please let me know if any of you have got any soultion.

Thanks
Sneha


回答1:


As you've probably determined, that's your virtual machine crashing. Nothing you do normally within Java should trigger this, and consequently I would start by upgrading your JVM. 1.6.0_03 is quite old.

This page details the Java 7 downloads, and the earlier Java 6 JDKs too. As you can see they're up to minor version 31 so you're relatively out-of-date.

If you want to debug this further, note the above error report file and check out this SO answer.




回答2:


The source file is correct, I try it and it works.

Only one error, but it is not related to your problem. You are using readLine() method. When you get the line and you append it to tempData you lose the line termination chars, so remember to fix this, or you alter the file.



来源:https://stackoverflow.com/questions/10104655/simple-java-class-to-download-the-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!