
import java.net.*;
import java.io.*;
public class CopyURL {
// copy url to local file name
public static void copy(String urlname, String filename) throws Exception {
URL url = new URL(urlname);
File file = new File(filename);
BufferedInputStream in = new BufferedInputStream(url.openConnection().getInputStream());
FileOutputStream out = new FileOutputStream(file);
int ch = 0;
while((ch = in.read())!=-1) {
out.write(ch);
}
in.close();
out.close();
}
public static void main(String[] args) throws Exception {
String urlname = "http://www.charlesli.org/index.html";
String filename = "test.html";
copy(urlname, filename);
}
}
http://www.charlesli.org/index.html
to a local file test.htmlThere are some drawbacks about the previous example
import java.net.*;
import java.io.*;
public class CopyURL2 {
// copy url to local file name
public static void copy(String urlname, String filename) throws Exception {
URL url = new URL(urlname);
File file = new File(filename);
BufferedInputStream in = new BufferedInputStream(url.openConnection().getInputStream());
FileOutputStream out = new FileOutputStream(file);
int ch = 0;
while((ch = in.read())!=-1) {
out.write(ch);
}
in.close();
out.close();
}
public static void main(String[] args) throws Exception {
String urlname = "http://www.charlesli.org/index.html";
String filename = "folder/test.html";
File file = new File(filename);
if(file.exists()) {
// file already exists, what do you want to do?
// my program prints out an error message and exit
System.out.println(filename + " exists.");
return; // quit the main
}
file.getParentFile().mkdirs(); // make all the necessary folders
copy(urlname, filename);
}
}
http://www.charlesli.org/index.html
to a local file folder/test.html