java 使用ftp下载远程服务器文件

第一种方法连接中带有账号密码直接远程下载:

    public Result<?> download(){
		//进行下载文件---------------------------------开始
        //远程服务器下载地址
        String fileurl = "ftp://superAdmin:superAdmin123@192.168.1.8:8888/usr/mp4pt/rec/CHN0/10110120011100/00001.mp4";
        //文件物理路径
        String realfilepath = "F:/rhsftdemo/00001.mp4";
        //本地中新建文件夹目录
        File file = new File("F:/rhsftdemo/");
        if (!file.exists()) {
            file.mkdirs();
        }
        log.info("存储路径realfilepath:" + realfilepath + "下载路径:" + fileurl);
        download(fileurl,realfilepath);
        return Result.ok();
    }

    private static final int BUFFER_SIZE = 4096;
    public void download(String ftpUrl,String savePath){
        long startTime = System.currentTimeMillis();
//        String ftpUrl = "ftp://ftp.f-secure.com/misc/unixutil/skeysrcs.zip";
        String file = "";
        // name of the file which has to be download
        String host = ""; // ftp server
        String user = ""; // user name of the ftp server
        String pass = ""; // password of the ftp server
//        String savePath = "F:\\skeysrcs.zip";
        ftpUrl = String.format(ftpUrl, user, pass, host);
        System.out.println("Connecting to FTP server");
        try {
            URL url = new URL(ftpUrl);
            URLConnection conn = url.openConnection();
            InputStream inputStream = conn.getInputStream();
            long filesize = conn.getContentLength();
            System.out.println("Size of the file to download in kb is:-" + filesize / 1024);
            FileOutputStream outputStream = new FileOutputStream(savePath);
            byte[] buffer = new byte[BUFFER_SIZE];
            int bytesRead = -1;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            long endTime = System.currentTimeMillis();
            System.out.println("File downloaded");
            System.out.println("Download time in sec. is:-" + (endTime - startTime) / 1000);
            outputStream.close();
            inputStream.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

第二种方法:通过账号密码登录后进行下载:


   public Result<?> download(){
        //进行下载文件---------------------------------开始
        //远程服务器下载地址
        String fileurl = "ftp://192.168.1.8:8888/usr/mp4pt/rec/CHN0/20220420095100/00001.mp4";
        //本地文件物理路径
        String realfilepath = "F:/rhsftdemo/00001.mp4";
        //本地中新建文件夹目录
        File file = new File("F:/rhsftdemo/");
        if (!file.exists()) {
            file.mkdirs();
        }
        log.info("存储路径realfilepath:" + realfilepath + "下载路径:" + fileurl);
        boolean bb = retepasvfile(realfilepath,fileurl,"00001.mp4");
        return Result.ok();
    }


/**
     * 本地保存
     *
     * @param localurl 本地文件物理路径
     * @param hosturl 远程服务器下载地址
     * @param filename 文件名称
     *
     * @return
     */
    public synchronized boolean retepasvfile(String localurl, String hosturl, String filename) {
        FTPClient ftp = new FTPClient();
        boolean re = false;
        try {
            log.info("本地存储路径==:" + localurl);
            File file = FileUtil.getFile(localurl);
            ftp.setConnectTimeout(10000);
            ftp.setDataTimeout(10000);
            ftp.connect("192.168.1.8", 21);
            if (!org.springframework.util.StringUtils.isEmpty("admin") && !org.springframework.util.StringUtils.isEmpty("superAdmin123") && "superAdmin" != "null" && "superAdmin123" != "null") {
                //这里输入账号密码
                ftp.login("superAdmin", "superAdmin123");
            } else {
                log.info("开始链接ftp:");
                ftp.login("anonymous", "anonymous");
            }

            //ftp.bin();
            //  String str=ftp.pwd();
            ftp.enterLocalPassiveMode(); //被动模式
            ftp.setControlKeepAliveTimeout(60);
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            boolean b = ftp.changeWorkingDirectory(hosturl.substring(0, hosturl.lastIndexOf("/")));
            log.info("pwd:" + b + "---切换目录:" + hosturl.substring(0, hosturl.lastIndexOf("/")));
            long locationsize = file.length();//服务器上文件的大小
            if (b) {
                boolean res = false;
                res = ftp.retrieveFile(filename, new FileOutputStream(file));
                if (res) {
                    //ftp.disconnect();
                    log.info("文件下载完成");
                    re = true;
                } else {
                    log.info("文件下载失败");
                    //ftp.disconnect();
                }
            }
        } catch (Exception e) {
            e.getStackTrace();

            log.error("retepasvfileSamba:e=3" + e);
        } finally {
            try {
                ftp.disconnect();
            } catch (Exception e) {
            }
        }
        return re;
    }
  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用Java实现FTP下载远程服务器指定目录下所有文件的示例代码: ```java import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.SocketException; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPReply; public class FTPDownloadDemo { public static void main(String[] args) { String server = "your.ftp.server.com"; int port = 21; String user = "username"; String password = "password"; String remoteDirPath = "/remote/directory/path"; String localDirPath = "/local/directory/path"; FTPClient ftpClient = new FTPClient(); try { // 连接FTP服务器 ftpClient.connect(server, port); // 登录FTP服务器 ftpClient.login(user, password); // 检查连接和登录是否成功 int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); System.err.println("FTP server refused connection."); return; } System.out.println("Connected to FTP server."); // 切换到指定目录 ftpClient.changeWorkingDirectory(remoteDirPath); // 获取指定目录下的所有文件 FTPFile[] files = ftpClient.listFiles(); for (FTPFile file : files) { if (file.isFile()) { // 下载文件 downloadFile(ftpClient, file.getName(), localDirPath); } } // 登出FTP服务器 ftpClient.logout(); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } } /** * 下载文件 * @param ftpClient FTP客户端 * @param fileName 文件名 * @param localDirPath 本地目录路径 * @throws IOException */ private static void downloadFile(FTPClient ftpClient, String fileName, String localDirPath) throws IOException { FileOutputStream fos = null; try { fos = new FileOutputStream(localDirPath + "/" + fileName); ftpClient.retrieveFile(fileName, fos); } finally { if (fos != null) { fos.close(); } } } } ``` 需要注意的是,上述代码使用了Apache Commons Net库来实现FTP操作,需要在项目中引用该库。可以从Apache官网下载该库或者通过Maven等构建工具添加依赖。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值