Java 如何將網(wǎng)絡資源url轉化為File文件
更新時間:2021年09月16日 10:33:56 作者:狂風之力
這篇文章主要介紹了Java 如何將網(wǎng)絡資源url轉化為File文件的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
將網(wǎng)絡資源url轉化為File文件
將互聯(lián)網(wǎng)上的http開頭的url資源,保存到本地。
private File getNetUrlHttp(String path){
//對本地文件命名,path是http的完整路徑,主要得到資源的名字
String newUrl = path;
newUrl = newUrl.split("[?]")[0];
String[] bb = newUrl.split("/");
//得到最后一個分隔符后的名字
String fileName = bb[bb.length - 1];
//保存到本地的路徑
String filePath="e:\\audio\\"+fileName;
File file = null;
URL urlfile;
InputStream inputStream = null;
OutputStream outputStream = null;
try{
//判斷文件的父級目錄是否存在,不存在則創(chuàng)建
file = new File(filePath);
if(!file.getParentFile().exists()){
file.getParentFile().mkdirs();
}
try{
//創(chuàng)建文件
file.createNewFile();
}catch (Exception e){
e.printStackTrace();
}
//下載
urlfile = new URL(newUrl);
inputStream = urlfile.openStream();
outputStream = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead=inputStream.read(buffer,0,8192))!=-1) {
outputStream.write(buffer, 0, bytesRead);
}
}catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (null != outputStream) {
outputStream.close();
}
if (null != inputStream) {
inputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return file;
}
url轉變?yōu)?MultipartFile對象
/**
* url轉變?yōu)?MultipartFile對象
* @param url
* @param fileName
* @return
* @throws Exception
*/
private static MultipartFile createFileItem(String url, String fileName) throws Exception{
FileItem item = null;
try {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setReadTimeout(30000);
conn.setConnectTimeout(30000);
//設置應用程序要從網(wǎng)絡連接讀取數(shù)據(jù)
conn.setDoInput(true);
conn.setRequestMethod("GET");
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream is = conn.getInputStream();
FileItemFactory factory = new DiskFileItemFactory(16, null);
String textFieldName = "uploadfile";
item = factory.createItem(textFieldName, ContentType.APPLICATION_OCTET_STREAM.toString(), false, fileName);
OutputStream os = item.getOutputStream();
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
is.close();
}
} catch (IOException e) {
throw new RuntimeException("文件下載失敗", e);
}
return new CommonsMultipartFile(item);
}
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
springcloud連接遠程nacos失敗顯示localhost服務連接失敗的問題解決
這篇文章主要介紹了springcloud連接遠程nacos失敗顯示localhost服務連接失敗的問題解決,文中有詳細的代碼示例供大家參考,對大家解決問題有一定的幫助,需要的朋友可以參考下2024-03-03
如何使用Java給您的圖片瘦身之Thumbnailator技術
在java日常開發(fā)中經(jīng)常遇到對圖片資源的操作需求,如壓縮、縮放、旋轉,下面這篇文章主要給大家介紹了關于如何使用Java給您的圖片瘦身之Thumbnailator技術的相關資料,需要的朋友可以參考下2022-10-10
Java反射(JDK)與動態(tài)代理(CGLIB)詳解
下面小編就為大家?guī)硪黄獪\談Java反射與動態(tài)代理。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2021-08-08

