java http下载文件/上传文件保存
生活随笔
收集整理的這篇文章主要介紹了
java http下载文件/上传文件保存
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
private boolean downloadFile(String httpUrl, String savePath) {
int byteread = 0;
try {
URL url = new URL(httpUrl);
URLConnection conn = url.openConnection();
InputStream inStream = conn.getInputStream();
FileOutputStream fs = new FileOutputStream(savePath);
byte[] buffer = new byte[1204];
while ((byteread = inStream.read(buffer)) != -1) {
fs.write(buffer, 0, byteread);
}
System.out.println(savePath+" download finished!");
return true;
} catch (MalformedURLException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
上傳文件保存在服務(wù)器:
private String saveFile(MultipartFile file) {
try {
if(file != null && !file.isEmpty()) {
String filePath = "保存至服務(wù)器的地址"
File fp = new File(new File(filePath).getParent());
if(!fp.exists()){
fp.mkdirs();
}
DataOutputStream out = new DataOutputStream(new FileOutputStream(filePath));
InputStream is = null;
try {
is = file.getInputStream();
byte[] b=new byte[is.available()];
is.read(b);
out.write(b);
return filePath ;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (is != null) {
is.close();
}
if (out != null) {
out.close();
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return null;
}
總結(jié)
以上是生活随笔為你收集整理的java http下载文件/上传文件保存的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何处理SAP Launchpad上ti
- 下一篇: 手机泡水了还能修吗