根据url下载到指定位置

问题引入

1.给定一个url,如果将资源下载到指定位置
2.如何将本地资源,上传到服务器上
3.如何将资源从一个服务器上传到另外一个服务器上。

例如:随着企业级开发的进行,文件上传和导入是非常常见的,那如何实现通过url下载资源到指定位置呢?

一、给定一个url,将资源下载到指定位置

1.1 注意事项

  • 判断资源是否纯在,如果不存在记得收集
  • 如果是在定时任务中,记得将重复的url进行过滤(解决方案:布隆过滤器,全局map)
  • 一定要做try,catch处理,在finally中进行流资源的释放
  • 日志一定要打印
try {
    			//jdk提供有专门处理api
                URL uri = new URL(url);
                //打开链接
                HttpURLConnection urlConnection = (HttpURLConnection) uri.openConnection();
    
    			//校验给定url的资源是否纯在
                int responseCode = urlConnection.getResponseCode();
                //判断url对应的文件是否存在
                if (HttpURLConnection.HTTP_OK != responseCode) {
                    failUrlList.add(url);
                    continue;
                }
                //判断该url下的资源是否已经迁移
                if (map.containsKey(url)) {
                    continue;
                }
                map.put(url, url);
                //获取流
                inputStream = urlConnection.getInputStream();
                //获取域名后的索引位置
                int i = url.indexOf(".com/");
                //如果文件不存在,就进行创建
                File file = new File(url.substring(i + 4, url.lastIndexOf("/")));
    			//只能创建目录或文件夹,一定不要把文件路径也加上啊!
                if (!file.exists()) {
                    file.mkdirs();
                }
    			//将资源写到指定位置上
                fileOutputStream = new FileOutputStream(url.substring(i + 4));
                byte[] bytes = new byte[1024];
                int length;
                while ((length = inputStream.read(bytes)) != -1) {
                    fileOutputStream.write(bytes, 0, length);
                }
            } catch (Exception e) {
                logger.info("迁移url=" + url + " 出现异常");
                e.printStackTrace();
            } finally {
                if (fileOutputStream != null) {
                    try {
                        fileOutputStream.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                        System.out.println("文件输入流关闭错误");
                    }
                }
            }

二、如何将本地资源,上传到服务器上

  • 三中工具类,能实现啊!!!!!!

image-20220811171058480


三、如何将资源从一个服务器上传到另外一个服务器上。

3.1 思路

  • 1.从服务器a上下载到本地,再从本地上传到服务器b
  • 2.直接将资源以流的形式传输到指定服务器上。

3.2注意事项

  • 判断资源是否纯在,如果不存在记得收集
  • 如果是在定时任务中,记得将重复的url进行过滤(解决方案:布隆过滤器,全局map)
  • 一定要做try,catch处理,在finally中进行流资源的释放
  • 日志一定要打印
//建立服务器的连接
ChannelSftp ftp = FtpUtils.getConnect(host, port, username, password);
			String url = "XXXXXX";
            logger.info("连接" + host + "主机成功");
            String filePath = "/usr/ceshi/";
                HttpURLConnection conn = null;
                InputStream inputStream = null;
                try {
                    // 建立链接
                    URL httpUrl = new URL(url);
                    conn = (HttpURLConnection) httpUrl.openConnection();
                    //以Post方式提交表单,默认get方式
                    conn.setDoInput(true);
                    conn.setDoOutput(true);
                    // post方式不能使用缓存
                    conn.setUseCaches(false);
                    //连接指定的资源
                    conn.connect();
                    //获取网络输入流
                    inputStream = conn.getInputStream();
                    logger.info("获取流资源成功");

                    //判断文件的保存路径后面是否以/结尾
                    if (!filePath.endsWith("/")) {
                        filePath += "/";
                    }
                    //上传文件
                    FtpUtils.uploadFile(inputStream, filePath, url.substring(url.lastIndexOf("/") + 1));
                    logger.info("上传文件" + url.substring(url.lastIndexOf("/") + 1) + "成功");
                    conn.disconnect();
                } catch (Exception e) {
                    e.printStackTrace();
                }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                FtpUtils.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

3.3 工具类上传和下载(可以直接拿来用)

package com.dajia.zlb.util;

import com.dajia.householdv2.timer.FileMoveTimer;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;

import java.io.*;
import java.util.Properties;

public class FtpUtils {

    private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(FtpUtils.class);

    /**
     * FTPClient对象
     **/
    private static ChannelSftp ftpClient = null;
    /**
     *
     */
    private static Session sshSession = null;

    /**
     * 连接服务器
     *
     * @param host
     * @param port
     * @param userName
     * @param password
     * @return
     * @throws Exception
     */
    public static ChannelSftp getConnect(String host, String port, String userName, String password)
            throws Exception {
        try {
            JSch jsch = new JSch();
            // 获取sshSession
            sshSession = jsch.getSession(userName, host, Integer.parseInt(port));
            // 添加s密码
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            // 开启sshSession链接
            sshSession.connect();
            // 获取sftp通道
            ftpClient = (ChannelSftp) sshSession.openChannel("sftp");
            // 开启
            ftpClient.connect();
            logger.info("success ..........");
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("连接sftp服务器异常。。。。。。。。");
        }
        return ftpClient;
    }

    /**
     * 下载文件
     *
     * @param ftp_path    服务器文件路径
     * @param save_path   下载保存路径
     * @param oldFileName 服务器上文件名
     * @param newFileName 保存后新文件名
     * @throws Exception
     */
    public static void download(String ftp_path, String save_path, String oldFileName, String newFileName)
            throws Exception {
        FileOutputStream fos = null;
        try {
            ftpClient.cd(ftp_path);
            File file = new File(save_path);
            if (!file.exists()) {
                file.mkdirs();
            }
            String saveFile = save_path + newFileName;
            File file1 = new File(saveFile);
            fos = new FileOutputStream(file1);
            ftpClient.get(oldFileName, fos);
        } catch (Exception e) {
            logger.info("下载文件异常............", e.getMessage());
            throw new Exception("download file error............");
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new Exception("close stream error..........");
                }
            }
        }
    }

    /**
     * 上传
     *
     * @param upload_path 上传文件路径
     * @param ftp_path    服务器保存路径
     * @param newFileName 新文件名
     * @throws Exception
     */
    public static void uploadFile(InputStream fis, String ftp_path, String newFileName) throws Exception {
        try {
            ftpClient.cd(ftp_path);
            ftpClient.put(fis, newFileName);
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("Upload file error.");
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new Exception("close stream error.");
                }
            }
        }
    }

    /**
     * 关闭
     *
     * @throws Exception
     */
    public static void close() throws Exception {
        logger.info("close............");
        try {
            ftpClient.disconnect();
            sshSession.disconnect();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new Exception("close stream error.");
        }
    }

    public static void main(String[] args) {
        try {
            getConnect("ip地址", "22", "用户名", "密码");
            close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

  • 如果不能使用api,引入相关依赖
<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.51</version>
</dependency>
     close();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

}


* 如果不能使用api,引入相关依赖

```pom
<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.51</version>
</dependency>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值