Created
March 23, 2012 21:38
-
-
Save StlTenny/2175334 to your computer and use it in GitHub Desktop.
FTP Upload
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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