I want to make a Java downloader program, which will download the data from the url to some local default folder, such as /tmp/data.
However, if the url is like: http://www.site.com/book/1.html, I want to save the file 1.html into /tmp/data/book/1.html.
I don’t know how to mkdir recursively, by which I mean make the “book” folder automatically.
The code I make the program to make file is like this:
String dataDir = "/tmp/data";
URL url = new URL("http://www.site.com/book/1.html");
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(dataDir+url.getFile())));
bw.write(data.toString());
bw.close();
You can use
mkdirs:As you see I also use
Fileto represent every path, for the sake of type safety and clearness.Last but not least: if you simply download a HTML file, I’d not use a
Stringto hold its content, because to get the correctStringyou’d need to know the HTML files encoding. It’s much easier to just handle it as abyte[], which avoids all the encoding-related problems.