Java根据URL下载文件到指定目录

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/yLazL0000/article/details/84654860

        根据url获取HttpURLConnection连接类,获取连接中的文件流,再通过输出流把文件内容输出到一个数组中,然后通过输出流输出到指定目录的文件。

以下是测试代码:

package com.test;


import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;



public class Test {
	
	@SuppressWarnings("finally")
	public static File downloadFile(String urlPath, String downloadDir) {
		File file = null;
		try {
			
			URL url = new URL(urlPath);
			
			URLConnection urlConnection = url.openConnection();
			
			HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;// http的连接类
		
			//String contentType = httpURLConnection.getContentType();//请求类型,可用来过滤请求,
			
			httpURLConnection.setConnectTimeout(1000*5);//设置超时
			
			httpURLConnection.setRequestMethod("POST");//设置请求方式,默认是GET
			
			httpURLConnection.setRequestProperty("Charset", "UTF-8");// 设置字符编码
			
			
			httpURLConnection.connect();// 打开连接
			
			BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());
			
			String fileName = "1.xlsx";// 指定文件名称
			
			String path = downloadDir + File.separatorChar + fileName;// 指定存放位置
			file = new File(path);
			// 校验文件夹目录是否存在,不存在就创建一个目录
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
 
			OutputStream out = new FileOutputStream(file);
			int size = 0;
			
			byte[] b = new byte[2048];
			//把输入流的文件读取到字节数据b中,然后输出到指定目录的文件
			while ((size = bin.read(b)) != -1) {
				out.write(b, 0, size);
			}
			// 关闭资源
			bin.close();
			out.close();
			System.out.println("文件下载成功!");
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("文件下载失败!");
		} finally {
			return file;
		}
 
	}

	
	public static void main(String[] args) {
		
		downloadFile("url", "/Users/xxxxx/Desktop/");// 指定资源地址,下载文件测试
        
	}
	
	
}

猜你喜欢

转载自blog.csdn.net/yLazL0000/article/details/84654860
今日推荐