package com.fusion.common.file;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
public class FileUtils {
/**
* @Description: 网络资源转file,用完以后必须删除该临时文件
* @param fileUrl 资源地址
* @author: 赵兴炎
* @date: 2019年7月10日
* @return: 返回值
*/
public static File urlToFile(String fileUrl) {
String path = System.getProperty("user.dir");
File upload = new File(path, "tmp");
if (!upload.exists()) {
upload.mkdirs();
}
return urlToFile(fileUrl,upload);
}
/**
* @Description: 网络资源转file,用完以后必须删除该临时文件
* @param fileUrl 资源地址
* @param upload 临时文件路径
* @author: 赵兴炎
* @date: 2019年7月10日
* @return: 返回值
*/
public static File urlToFile(String fileUrl,File upload) {
String fileName = fileUrl.substring(fileUrl.lastIndexOf("/"));
FileOutputStream downloadFile = null;
InputStream openStream = null;
File savedFile = null;
try {
savedFile = new File(upload.getAbsolutePath() + fileName);
URL url = new URL(fileUrl);
java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
openStream = connection.getInputStream();
int index;
byte[] bytes = new byte[1024];
downloadFile = new FileOutputStream(savedFile);
while ((index = openStream.read(bytes)) != -1) {
downloadFile.write(bytes, 0, index);
downloadFile.flush();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (openStream != null) {
openStream.close();
}
if (downloadFile != null) {
downloadFile.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return savedFile;
}
public static void main(String[] args) {
String mg="http://pic31.nipic.com/20130728/3822951_140613063000_2.jpg";
File urlToFile = urlToFile(mg);
System.out.println(urlToFile.getAbsolutePath());
urlToFile.delete();
}
}