venerdì 28 febbraio 2014

Upload & Download file from an ftp server in java > Java

Let's see how easy it's to download/upload a file in java via ftp. It's a really simple task, however it might still be helpful to anyone not so familiar with the ftp protocol. First off, for this code I've used commons.net library from apache, it's a pretty cool library, the only problem I've had so far was about some strange issue it had by downloading file from ftp in linux (fixed in the 3.3 version).

Let's create a class called ScambioFtp, we'll use it to call two function to download/upload files from a specific ftp server.


import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.io.CopyStreamAdapter;

public class ScambioFtp {

 FTPClient ftp = null;
 
 public ScambioFtp(String host, String user, String pass) throws Exception
 {
                //host can either be ad url or an ip address
  ftp = new FTPClient();  //The object we'll use to connect to our ftp server
  ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); //We ensure to get the messages from the server and we redirect it to our console output stream
  ftp.connect(host);
  int reply = ftp.getReplyCode();
  if(!FTPReply.isPositiveCompletion(reply))
  {
   ftp.disconnect();
   throw new Exception("Problem during the connection to the host: " + host);
  }
  if(!ftp.login(user, pass))
  {
   ftp.disconnect();
   throw new Exception("Login problem, wrong user or password");
  }
 }
 
 /**
  * Upload a file in the current ftp filesystem directory
  * @param filePath
  * @throws IOException 
  */
 public void uploadFile(String filePath) throws IOException
 {
  try
  {
   File vab = new File(filePath);
   String fileName = vab.getName();
   FileInputStream input = new FileInputStream(vab);
   ftp.storeFile(fileName, input); //start upload
  }catch (Exception e) {
   e.printStackTrace();
   System.out.println("Problem during upload of the file " + filePath);
  }
 }
 
 
 /**
  * Download of the fileName in the current directory of the ftp filesystem
  * @param fileName = name of the file to download from the server
  * @param path = local path where to save the downloaded file
  * @throws IOException 
  * @throws FileNotFoundException 
  */
 public void downloadFile(String fileName, String path) throws FileNotFoundException, IOException
 {
  String remoteFilePath = fileName;
  String localFilePath = path +"/"+ fileName;
  try(FileOutputStream fos = new FileOutputStream(localFilePath))
  {
   ftp.retrieveFile(remoteFilePath, fos);
  }catch (IOException e) {
   e.printStackTrace();
  }
 }
 
 
 /**
  * disconnect from the ftp
  */
 public void disconnect()
 {
  if(this.ftp.isConnected())
  {
   try
   {
    this.ftp.logout();
    this.ftp.disconnect();
   }catch (Exception e) {
    System.out.println("problem while disconnecting from ftp server");
   }
  }
 }

        public void openFolder(String folderName) throws IOException
 {
  
  if(!ftp.changeWorkingDirectory(folderName))
   System.out.println("Directory " + folderName + " not found");
 }
 
 //Use main to test this shit
 public static void main(String[] args) throws Exception
 {
  ScambioFtp ftp = new ScambioFtp("ftp.mine.org", Config._USERNAME, Config._FTP_PASSWORD);
  String ordfilePath = "res/ordini/0001.dat";
  ftp.uploadFile(ordfilePath);
  ftp.disconnect();
 }
}

That's pretty much it, you can easly copy-paste it and start using it right away. if you want to use passive mode or some other configuration you can access a lot of methods from FTPClient.

Nessun commento:

Posta un commento