文件上传下载
Java文件上传和下载对于刚接触Java没多久的老铁们来说可能是一个技术难点。如果看过我前两篇文章的老铁肯定就知道,这次肯定又是一个工具类,废话少说我们直接附上代码。
package com.fashion.fox.ctr;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import com.fashion.fox.ctr.Constant;
@Component
public class LoadUtils {
public boolean downLoadFromUrl(String urlStr, String savePath) {
OutputStream os = null;
InputStream inputStream = null;
try {
URL url = new URL(urlStr);
String end = urlStr.trim();
for (int i = 0; i < urlStr.length(); i++) {
int index = end.indexOf(".");
if (index < 0) {
break;
}
end = end.substring(index + 1);
}
String fileName = UUID.randomUUID().toString() + "." + end;
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(3 * 1000);
conn.setRequestProperty(Constant.USERAGENT, Constant.MOZILLA);
inputStream = conn.getInputStream();
byte[] bs = new byte[1024];
int len;
File tempFile = new File(savePath);
if (!tempFile.exists()) {
tempFile.mkdirs();
}
os = new FileOutputStream(tempFile.getPath() + File.separator + fileName);
while ((len = inputStream.read(bs)) != -1) {
os.write(bs, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
try {
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return true;
}
public boolean upLoad(MultipartFile file, String savePath, String FileName) {
OutputStream os = null;
InputStream inputStream = null;
String fileName = null;
try {
String imgeAfter = file.getOriginalFilename();
imgeAfter = imgeAfter.substring(imgeAfter.indexOf("."));
inputStream = file.getInputStream();
fileName = FileName + imgeAfter;
byte[] bs = new byte[1024];
int len;
File tempFile = new File(savePath);
if (!tempFile.exists()) {
tempFile.mkdirs();
}
os = new FileOutputStream(tempFile.getPath() + File.separator + fileName);
while ((len = inputStream.read(bs)) != -1) {
os.write(bs, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
try {
os.close();
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return true;
}
}