Upload File to FTP Server Using Java


How to upload file to FTP Server ?

Reference : here

We need FTP jar. You can find it in reference.


package file.ftp.upload;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import org.apache.commons.net.ftp.FTPClient;

public class UploadFileFTP {
public static void main(String[] args) {
FTPClient ftpClient = new FTPClient();
FileInputStream fis = null;
String hostname = “[Path for FTP Server]”;
int port = 21;
String user = “[user login]”;
String pass = “[password login]”;
String fileName=null;
File folder = new File(“D:/ftp/process/”); //Directory from local
File[] listOfFiles = folder.listFiles();
try {
ftpClient.connect(hostname, port);
boolean login = ftpClient.login(user, pass);
if(login){
System.out.println(“Connection established…”);
for (File fileDownload : listOfFiles) {
if (fileDownload.isFile()) {
fileName = fileDownload.getName();
System.out.println(“Nama file : “+fileName);
File uploadToCurrent = new File(“D:/ftp/process/”+fileName);
String filePath = uploadToCurrent.getAbsolutePath();
System.out.println(“Path file : “+filePath);
fis = new FileInputStream(filePath);
//Path from FTP Server
String uploadPath = “Current/”+fileName;
System.out.println(uploadPath);
System.out.println(“Start uploading first file”);
boolean done = ftpClient.storeFile(uploadPath, fis);
fis.close();
if (done) {
System.out.println(“The first file is uploaded successfully.”);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
}finally{
try {
if (ftpClient.isConnected()) {
boolean logout = ftpClient.logout();
ftpClient.disconnect();
if (logout) {
System.out.println(“Connection close…”);
} else {
System.out.println(“Connection fail…”);
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.