如何使用Java压缩SFTP或FTP服务器中的文件?

问题描述 投票:4回答:1

我能够压缩本地计算机中的文件,但我想通过Java在SFTP服务器中压缩(.zip)文件。如何传递URL以及如何压缩SFTP或FTP服务器中的文件?

下面是我的本地系统,我需要在SFTP中实现同样的功能。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class CompressToZip {

    public static void main(String[] args) throws Exception{
        String pattern = "ddMMyyyy";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        String date = simpleDateFormat.format(new Date());
        System.out.println(date);
        String sourceFolderName =  "C:\\Users\\Desktop\\BackUpFiles\\"+date;

        File folder = new File("C:\\Users\\Desktop\\BackUpFileZip");
        String outputFileName = folder+"\\"+date+".zip";
        if(!folder.exists()){
            folder.mkdir();
        }else{
            System.out.println("Folder Exist.....");
        }


        System.currentTimeMillis();
        FileOutputStream fos = new FileOutputStream(outputFileName);
        ZipOutputStream zos = new ZipOutputStream(fos);
        //level - the compression level (0-9)
        zos.setLevel(9);

        System.out.println("Begin to compress folder : " + sourceFolderName + " to " + outputFileName);
        addFolder(zos, sourceFolderName, sourceFolderName);

        zos.close();
        System.out.println("Program ended successfully!");
    }

    private static void addFolder(ZipOutputStream zos,String folderName,String baseFolderName)throws Exception{
        File f = new File(folderName);
        if(f.exists()){

            if(f.isDirectory()){
                //Thank to peter 
                //For pointing out missing entry for empty folder
                if(!folderName.equalsIgnoreCase(baseFolderName)){
                    String entryName = folderName.substring(baseFolderName.length()+1,folderName.length()) + File.separatorChar;
                    System.out.println("Adding folder entry " + entryName);
                    ZipEntry ze= new ZipEntry(entryName);
                    zos.putNextEntry(ze);    
                }
                File f2[] = f.listFiles();
                for(int i=0;i<f2.length;i++){
                    addFolder(zos,f2[i].getAbsolutePath(),baseFolderName);    
                }
            }else{
                //add file
                //extract the relative name for entry purpose
                String entryName = folderName.substring(baseFolderName.length()+1,folderName.length());
                System.out.print("Adding file entry " + entryName + "...");
                ZipEntry ze= new ZipEntry(entryName);
                zos.putNextEntry(ze);
                FileInputStream in = new FileInputStream(folderName);
                int len;
                byte buffer[] = new byte[1024];
                while ((len = in.read(buffer)) > 0) {
                    zos.write(buffer, 0, len);
                }
                in.close();
                zos.closeEntry();
                System.out.println("OK!");

            }
        }else{
            System.out.println("File or directory not found " + folderName);
        }

    }

}

如何提供SFTP或FTP服务器地址的sourceFolderNameoutputFileName

为了连接到SFTP,我使用下面的代码:

public class JschTestDownload {

  public static void main(String s[]) {

       JSch jsch = new JSch();

       Session session = null;
       // Remote machine host name or IP
       String hostName = "xxx.xxx.xx.xxx";
       // User name to connect the remote machine
       String userName = "xxxxx";
       // Password for remote machine authentication
       String password = "xxxx";    
       // Source file path on local machine
       String srcFilePath = "/Inbound/testSFTP.txt";
       // Destination directory location on remote machine

       String destinationLocation = "C:/Users/Desktop/SftpUpDown/TestDownload";
       try {
        // Getting the session
        session = jsch.getSession(userName, hostName,22);

        // Ignore HostKeyChecking
        session.setConfig("StrictHostKeyChecking", "no");                  

        // set the password for authentication
        session.setPassword(password);
        System.out.println("try to get the connection");
        session.connect();
        System.out.println("got the connection");            
        // Getting the channel using sftp
        Channel channel = session.openChannel("sftp");
        channel.connect();
        ChannelSftp sftpChannel = (ChannelSftp) channel;

        sftpChannel.cd("/Inbound/");


        // Exist the channel
         sftpChannel.exit();

         // Disconnect the session
         session.disconnect();

       } catch (JSchException e) {
              e.printStackTrace();

       } catch (SftpException e) {
              e.printStackTrace();
       }
     }
}

通过使用上面的代码,我能够获取文件和放置文件。但我想使用第一个代码压缩SFTP服务器中的文件。我需要在我的计算机上运行该代码并在服务器上压缩文件并下载到我的计算机。我该怎么做?给我一些指导。

java ftp sftp jsch zipfile
1个回答
1
投票

你不能。无法通过FTP或SFTP协议就地压缩文件。

您所能做的就是下载文件,在本地压缩并上传回来。你似乎能做什么​​。

这并不意味着您必须在本地(临时)存储文件。您可以使用流在内存中完成所有这些操作。


当然,如果您具有对服务器的shell访问权限,则可以使用SSH协议连接并运行zip(或类似)命令来压缩文件。但那不是SFTP / FTP。


相关问题:

© www.soinside.com 2019 - 2024. All rights reserved.