FileFromUrl

public class DownloadFileFromURLUtil {

    public static void main(String[] args) {
        String url = "https://www.yiibai.com/index.html";

        try {
            downloadUsingNIO(url, "D:/users/maxsu/sitemap.xml");

            downloadUsingStream(url, "D:/users/maxsu/sitemap_stream.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void downloadUsingStream(String urlStr, String file) throws IOException{
        URL url = new URL(urlStr);
        BufferedInputStream bis = new BufferedInputStream(url.openStream());
        FileOutputStream fis = new FileOutputStream(file);
        byte[] buffer = new byte[1024];
        int count=0;
        while((count = bis.read(buffer,0,1024)) != -1)
        {
            fis.write(buffer, 0, count);
        }
        fis.close();
        bis.close();
    }

    public static void downloadUsingNIO(String urlStr, String file) throws IOException {
        URL url = new URL(urlStr);
        ReadableByteChannel rbc = Channels.newChannel(url.openStream());
        FileOutputStream fos = new FileOutputStream(file);
        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        fos.close();
        rbc.close();
    }

}
上传文件
//将临时文件转存到指定位置
file.transferTo(new File(basePath + fileName));

下载文件
//输出文件
IOUtils.copy(new FileInputStream(file), response.getOutputStream());
//关闭流
IOUtils.closeQuietly(inputStream);
IOUtils.closeQuietly(outputStream);

日夜颠倒头发少 ,单纯好骗恋爱脑 ,会背九九乘法表 ,下雨只会往家跑 ,搭讪只会说你好 ---- 2050781802@qq.com

×

喜欢就点赞,疼爱就打赏

相册 说点什么