java读取网络文件并存储到本地
java读取网络上的图片,视频,音频包括其他的文件并且把他们存储到本地。我们知道,网络上的任何资源文件都是以二进制的方式存储的,一切文件皆是二进制的流文件,所以用java读取并存储非常的简单而且特别的实用,之后歌曲,图片,视频都可随意的下载,而且是批量的下载。
步骤1:
我们先获取一个资源文件的地址:
url=“https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fa2.att.hudong.com%2F27%2F81%2F01200000194677136358818023076.jpg&refer=http%3A%2F%2Fa2.att.hudong.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1613131631&t=38baca0898371b80c47543afb83ff52d”
步骤2:
使用java语言对这个地址进行连接并读取代码如下
HttpURLConnection httpUrl = (HttpURLConnection) new URL(url).openConnection();
httpUrl.connect();
InputStream inputStream = httpUrl.getInputStream();
这样我们就得到了一个文件流;不管是视频,图片,音频,文本文件,都是可以的
步骤3:
我们获取到流文件之后肯定要用一个数组取读取接收它,地球人都知道二进制流用byte数组去接收,byte数组就相当于我们的中间容器,而且我们要提前在自己本地建立一个文件取接受中间容器给我们的二进制数据。至于为什么要有中间容器?因为我们不确定读取的文件到底是多大,一次能不能读完,就好像盛饭用的小勺,从锅里面盛饭,要一勺一勺的试探性的去盛。具体的代码如下:
File file = new File("C:\\Users\\ccc\\Desktop\\cttata" + File.separator + name);
OutputStream os = new FileOutputStream(file);
int bytesRead;
int len = 1024;
byte[] buffer = new byte[len];
while ((bytesRead = ins.read(buffer, 0, len)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
这个就是读取一个文件并存储本地的方法,你以为就完了,那你就大错特错了,给你们分享我的工具类
package com.xiangmu.springcloud.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* @author ct
* @date 2021/1/13 19:53
*/
public class DownLoadImageFile {
/**
* 网络图片资源转本地文件
*
* @param url
* @return
* @throws Exception
*/
public static File getIamgeFile(String url, String name) throws Exception {
HttpURLConnection httpUrl = (HttpURLConnection) new URL(url).openConnection();
httpUrl.connect();
InputStream inputStream = httpUrl.getInputStream();
File file = inputStreamToFile(inputStream, constractImageName(name));
httpUrl.disconnect();
return file;
}
/**
* 工具类
* inputStream 转 File
*/
public static File inputStreamToFile(InputStream ins, String name) throws Exception {
File file = new File("C:\\Users\\xxxxx\\Desktop\\xxx" + File.separator + name);
if (file.exists()) {
String name1 = file.getName();
String name2 = name1.substring(0, name1.indexOf("."));
String suffix = name1.substring(name1.lastIndexOf("."));
int random = (int) (Math.random() * 1000 + 1);
String name3 = name2 + "(" + random + ")";
String s = name3 + suffix;
file = new File("C:\\Users\\xxxx\\Desktop\\xxx" + File.separator + s);
}
OutputStream os = new FileOutputStream(file);
int bytesRead;
int len = 1024;
byte[] buffer = new byte[len];
while ((bytesRead = ins.read(buffer, 0, len)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
return file;
}
public static String splitImageName(String originalUrl) {
String[] split = originalUrl.split("\\?");
String url = split[0];
int i = url.lastIndexOf('/');
String name = originalUrl.substring(i + 1);
if (name.contains(".")) {
return name;
}
return name + ".png";
}
}
赶快去试试吧,希望可以帮到大家!