下载网页文件到本地

package util;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;
import utils.ReadConfig;
import utils.SQLHelper;
public class Down {
private static String createPath = "";
private static String fileDirHead = "";//文件位置,如F\:\\test
private synchronized static String manageFilePath() {
if (createPath == null || "".endsWith(createPath)) {
createPath = fileDirHead + "\\";
new File(createPath).mkdirs();
}
File file = new File(createPath);
int length = file.list().length;
if (length >= 2000) {
createPath = fileDirHead + "\\";
new File(createPath).mkdirs();
}
return createPath;
}
public static void downloadAndSave(String source, String destination) {
try {
URL url = new URL(source); 
File file = new File(destination); 
FileUtils.copyURLToFile(url, file);
System.out.println(source + "下载完成");
} catch (MalformedURLException e) {
System.out.println("URL格式出错,请检查");
e.printStackTrace();
} catch (IOException e) {
System.out.println("I/O 错误");
e.printStackTrace();
}
}
public static void main(String[] args) {
String url = "文件下载链接";
String path = url.split("/")[url.split("/").length - 1].replace("'", "");//根据自己的需求截取文件名字带后缀
String des = manageFilePath() + path;//文件位置
downloadAndSave(url, des);
System.out.println("恭喜你,全部下载成功!");
}



}

你可能感兴趣的:(下载网页文件到本地)