/**
* 文件读取/写入
*
* @param urlStr 文件地址
* @param fileName 文件路径/名称
* @return
*/
public String storeFile(String urlStr, String fileName) {
try {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置超时间为10秒
conn.setConnectTimeout(10 * 1000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//得到输入流
InputStream inputStream = conn.getInputStream();
//获取自己数组
byte[] getData = readInputStream(inputStream);
String date = DateUtils.formats(new Date());
String savePath = tmp.concat("/").concat(date);
Path folderPath = Paths.get(savePath);
boolean desk = Files.exists(folderPath);
if (!desk) {
//不存在文件夹 => 创建
Files.createDirectories(folderPath);
}
String path = savePath + "/" + fileName;
Path filePath = Paths.get(path);
boolean exists = Files.exists(filePath, LinkOption.NOFOLLOW_LINKS);
if (!exists) {
//不存在文件 => 创建
Files.write(filePath, getData, StandardOpenOption.CREATE);
}
return path;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
}
URL请求 将文件 写入本地
于 2022-12-03 17:09:39 首次发布