java sftp 多文件上传下载 优化单文件上传下载

多文件上传:

  • fromPath:本地文件夹的路径
  • upToPath:服务器目标文件夹的路径

public int uploadFiles(String fromPath, String upToPath) {
        //多文件上传
        fromPath = judgePath(fromPath);
        upToPath = judgePath(upToPath);
        FileInputStream in = null;
        String fileName = null;
        String originPath = null;
        File folder = new File(fromPath);
        File[] listOfFiles = folder.listFiles();
        System.out.println(listOfFiles.length);
        try {
            if (listOfFiles == null){
                return 0;
            }
            for (File file :listOfFiles) {
                fileName = file.getName();
                if (fileName.equals(".") || fileName.equals("..")){
                    continue;
                }
                System.out.println(fileName);
                originPath = fromPath + fileName;
                System.out.println(originPath);
                in = new FileInputStream(new File(originPath));
                channelSftp.put(in,upToPath + fileName);
            }
        } catch (SftpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        try {
            in.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return listOfFiles.length;
    }

多文件下载:

  • downloadPath:服务器要下载的文件夹路径
  • toPath:下载到本地文件夹的路径

public int downloadFiles(String downlownPath, String toPath) {
        //多文件下载
        downlownPath = judgePath(downlownPath);
        toPath = judgePath(toPath);
        Vector files = null;
        InputStream download = null;
        ChannelSftp.LsEntry lsEntry = null;
        File file1 = null;
        String fileName = null;
        String destPath = null;
        try {
            files = channelSftp.ls(downlownPath);
            System.out.println(files.size()-2);
            if (files == null){
                return 0;
            }
            for (Object file :files) {
                lsEntry = (ChannelSftp.LsEntry)file;
                fileName = lsEntry.getFilename();
                if (fileName.equals(".") || fileName.equals("..")){
                    continue;
                }
                System.out.println(fileName);
                download = channelSftp.get(downlownPath + fileName);
                destPath = toPath + fileName;
                System.out.println(destPath);
                //把文件保存到本地
                file1 = new File(destPath);
                FileUtils.copyInputStreamToFile(download, file1);
            }
        } catch (SftpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        try {
            download.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return files.size()-2;
    }