Is this the best way to download a file in java?

后端 未结 4 1826
半阙折子戏
半阙折子戏 2021-01-07 07:20
public void download(String url, String destination) {
        BufferedOutputStream localBufferedOutputStream = null;
        URLConnection localURLConnection = null         


        
相关标签:
4条回答
  • 2021-01-07 07:36

    You can leave out the BufferedOutputStream since you're already using a buffer yourself. But that's not going to make a big difference.

    What may (or may not) make a big difference is using the nio channel classes instead of the streams.

    0 讨论(0)
  • 2021-01-07 07:38

    You should always look to libraries such as Apache. They have done all the hard work for you: http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html

    I use

    static String   readFileToString(File file)
              Reads the contents of a file into a String using the default encoding for the VM.
    

    quite a lot.

    If you know you have a URL (and so stream) look at: http://commons.apache.org/io/api-1.4/org/apache/commons/io/IOUtils.html

    0 讨论(0)
  • 2021-01-07 07:47

    It is certainly not the best way. Code that throws away all exceptions is rarely the best way to do any thing. You might also consider not usi g strings as parameters. URI and File would be good alternatives.

    If you want to copy streams transferTo is a good way.

    0 讨论(0)
  • 2021-01-07 07:48

    As an alternative and just for reference, you can investigate HTMLUnit. This framework will allow you to download files even on sites where there are browser redirects.

    http://htmlunit.sourceforge.net/

    0 讨论(0)
提交回复
热议问题