How does Java convert network resource url into File file
- 2021-11-14 05:40:53
- OfStack
Convert network resource url into File file
Save the url resources at the beginning of http on the Internet locally.
private File getNetUrlHttp(String path){
// Name the local file, path Yes http The full path of, mainly getting the name of the resource
String newUrl = path;
newUrl = newUrl.split("[?]")[0];
String[] bb = newUrl.split("/");
// Get the last 1 The name after the separator
String fileName = bb[bb.length - 1];
// Save to local path
String filePath="e:\\audio\\"+fileName;
File file = null;
URL urlfile;
InputStream inputStream = null;
OutputStream outputStream = null;
try{
// Determine whether the parent directory of the file exists, and create if it does not exist
file = new File(filePath);
if(!file.getParentFile().exists()){
file.getParentFile().mkdirs();
}
try{
// Create a file
file.createNewFile();
}catch (Exception e){
e.printStackTrace();
}
// Download
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 to MultipartFile Object
/**
* url Turn into MultipartFile Object
* @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);
// Setting the application to read data from a network connection
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(" File download failed ", e);
}
return new CommonsMultipartFile(item);
}