Skip to content

Instantly share code, notes, and snippets.

@StlTenny
Created March 23, 2012 21:38
Show Gist options
  • Save StlTenny/2175334 to your computer and use it in GitHub Desktop.
Save StlTenny/2175334 to your computer and use it in GitHub Desktop.
FTP Upload
private static void check(FTPClient ftp, String cmd, boolean succeeded) throws IOException {
if (!succeeded) {
throw new IOException("FTP error: " + ftp.getReplyString());
}
}
private static String today() {
return new SimpleDateFormat("yyyy-MM-dd").format(new Date());
}
public void uploadfile(String server, String username, String Password, String sourcePath, String destDir) throws IOException {
FTPClient ftp = new FTPClient();
ftp.connect(server);
try {
check(ftp, "login", ftp.login(username, Password));
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.setFileTransferMode(FTP.BINARY_FILE_TYPE);
ftp.setSoTimeout(10000);
ftp.enterLocalPassiveMode();
System.out.println("Connected to " + server + ".");
InputStream input = new FileInputStream(sourcePath);
try {
String destination = destDir;
if (destination.endsWith("/")) {
destination += today() + "-" + new File(sourcePath).getName();
}
check(ftp, "store", ftp.storeFile(destination, input));
System.out.println("Stored " + sourcePath + " to " + destination + ".");
} finally {
input.close();
}
check(ftp, "logout", ftp.logout());
} finally {
ftp.disconnect();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment