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(!file.getParentFile().exists()){

file.getParentFile().mkdirs();

}

try{

//创建文件

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转变为 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 (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);

}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

以上是 Java 如何将网络资源url转化为File文件 的全部内容, 来源链接: www.h5w3.com/249063.html

回到顶部