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

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

    Downloading a file requires you to read it, either way you will have to go through the file in some way. Instead of line by line, you can just read it by bytes from the stream:

    BufferedInputStream in = new BufferedInputStream(new URL("http://www.website.com/information.asp").openStream())
        byte data[] = new byte[1024];
        int count;
        while((count = in.read(data,0,1024)) != -1)
        {
            out.write(data, 0, count);
        }
    

提交回复
热议问题