pen1993
pen1993

Reputation: 231

How to compress file in SFTP or FTP server by using Java?

I am able to compress files in my local computer, but I want to compress (.zip) files in SFTP server through Java. How can I pass URL and how to compress the files in SFTP or FTP server?

Below one is my local system working same thing I need to implement in 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);
        }

    }

}

How can I give the sourceFolderName and outputFileName of SFTP or FTP server address?

For connecting to SFTP I am using below code:

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();
       }
     }
}

By using above code I am able to get file and put file. But I want to compress file in SFTP server by using first code. I need to run that code in my computer and compress file at server and download to my computer. How can I do it? Give me some guidance.

Upvotes: 4

Views: 5917

Answers (1)

Martin Prikryl
Martin Prikryl

Reputation: 202088

You cannot. There's no way to compress files in-place over the FTP or SFTP protocol.

All you can do is to download the file, compress locally and upload back. What you seem to be able to do.

That does not mean you have to store the file locally (temporarily). You can do all this in memory, using streams.


Of course, if you have a shell access to the server, you can connect with the SSH protocol and run a zip (or similar) command to compress the files. But that's not SFTP/FTP.


Related questions:

Upvotes: 1

Related Questions