注:这个是别人用过的 我只不过加了几个例子 整理一下
1.文件来源地址相应改掉
2.以这个为例,存储路径里必须有 test 这个文件夹 如果没有 加上这一段
File file = new File("E:\\test");
//如果文件夹不存在 就创建一个空的文件夹
if (!file.exists()) {
file.mkdirs();
}
package IOFile;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
/**
* 下载 文件 图片 视频 压缩包
*/
public class DownloadFile {
public static void main(String[] args) {
httpDownload("http://192.168.148.140:5080/test.txt", "E:\\test\\test.txt");
httpDownload("http://192.168.148.140:5080/0ae4d931-1544-4a2b-bb0d-3e2be3b5b926.jpg", "E:\\test\\test.jpg");
httpDownload("http://192.168.148.140:5080/20181220_133558.avi", "E:\\test\\test.avi");
httpDownload("http://192.168.148.140:5080/aa.zip", "E:\\test\\test.zip");
}
public static boolean httpDownload(String httpUrl, String saveFile) {
// 1.下载网络文件
int byteRead;
URL url;
try {
url = new URL(httpUrl);
} catch (MalformedURLException e1) {
e1.printStackTrace();
return false;
}
try {
//2.获取链接
URLConnection conn = url.openConnection();
//3.输入流
InputStream inStream = conn.getInputStream();
//3.写入文件
FileOutputStream fs = new FileOutputStream(saveFile);
byte[] buffer = new byte[1024];
while ((byteRead = inStream.read(buffer)) != -1) {
fs.write(buffer, 0, byteRead);
}
inStream.close();
fs.close();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}