Wednesday, September 30, 2015

FTP program in Java

This program receives a local file path and upload it. I used Jsch library to make this program, so if you want to use this program, you must download Jsch.jar file, then save the Jsch somewhere and set a classpath for the Jsch.jar file. This is difficult...But if you are using Eclipse, it is easy to set a classpath for an external library. Check here.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Locale;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class SFTPinJava {
public SFTPinJava() {

}

public static void main(String[] args) {
 String SFTPHOST = "your host";
 int SFTPPORT = portnumber;
 String SFTPUSER = "user_name";
 String SFTPPASS = "password";
 String SFTPWORKINGDIR = "location";

 Session session = null;
 Channel channel = null;
 ChannelSftp channelSftp = null;

 try{
   System.out.println("Enter the local path of the file which you want to upload:");

    BufferedReader input = new BufferedReader (new InputStreamReader (System.in));
    String str = input.readLine( );

         System.out.println("Your file's local path is: " + str);

   JSch jsch = new JSch();
   session = jsch.getSession(SFTPUSER,SFTPHOST,SFTPPORT);
   session.setPassword(SFTPPASS);
   java.util.Properties config = new java.util.Properties();
   config.put("StrictHostKeyChecking", "no");
   session.setConfig(config);
   session.connect();
   channel = session.openChannel("sftp");
   channel.connect();
   channelSftp = (ChannelSftp)channel;
   channelSftp.cd(SFTPWORKINGDIR);
   File f = new File((str));
   channelSftp.put(new FileInputStream(f), f.getName());

   SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.JAPAN);

   System.out.println("File transfered successfully to host.");
   System.out.println("Name: " + f.getName());
   System.out.println("Path: " + f.getPath());
   System.out.println("File size: " + (getKB(f.length())) + "KB");
   System.out.println("Extension: " + getSuffix(f.getName()));
   System.out.println("File last Modified time: " + sdf.format(f.lastModified()));
  }catch(Exception ex){
  ex.printStackTrace();
  }
 }

  private static String getSuffix(String fileName) {
   if (fileName == null)
         return null;
      int point = fileName.lastIndexOf(".");
      if (point != -1) {
          return fileName.substring(point + 1);
      }
      return fileName;
  }

  private static double getKB(long byte1){
   double kbyte1;
   double byte2;
   byte2 = byte1;

   kbyte1 = byte2/1024;
   return kbyte1;
  }
}