Java如何将⽹络资源url转化为File⽂件将⽹络资源url转化为File⽂件
将互联⽹上的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{
//判断⽂件的⽗级⽬录是否存在,不存在则创建
file = new File(filePath);
if(!ParentFile().exists()){
}
try{
/
/创建⽂件
}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 ((ad(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转变为 MultipartFile对象
/**
* url转变为 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);
/
/设置应⽤程序要从⽹络连接读取数据
conn.setDoInput(true);
conn.setRequestMethod("GET");
if (ResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream is = InputStream();
FileItemFactory factory = new DiskFileItemFactory(16, null);
String textFieldName = "uploadfile";
item = ateItem(textFieldName, ContentType.APPLICATION_String(), false, fileName);            OutputStream os = OutputStream();
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);
}
以上为个⼈经验,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。java学习资源

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。