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 and reading online files (URLs) line-by-line, but is there a way to just download and save the file using Java?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
There is an issue with simple usage of:
if you need to download and save very large files, or in general if you need automatic retries in case connection is dropped.
What I suggest in such cases is Apache HttpClient along with org.apache.commons.io.FileUtils. For example:
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:
This answer is almost exactly like selected answer but with two enhancements: it's a method and it closes out the FileOutputStream object:
If you are behind a proxy, you can set the proxies in java program as below:
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.
It's an old question but here's an elegant JDK-only solution:
Concise, readable, properly closed resources leveraging nothing but the core JDK and language features.
Simpler nio usage: