Skip to content

Instantly share code, notes, and snippets.

@xie-qianyue
Last active October 15, 2021 22:23
Show Gist options
  • Save xie-qianyue/96ac3136f333a3feb0f5 to your computer and use it in GitHub Desktop.
Save xie-qianyue/96ac3136f333a3feb0f5 to your computer and use it in GitHub Desktop.
Java FTP/SFTP Client
public class DownloadFileService {
private static final Logger logger = LogManager.getLogger(DownloadFileService.class);
public static boolean download(final String[] lesFichiers, final String inputFolder, final String outputFolder,
final String suffix, final String server, final int port, final String user, final String pass) {
boolean success = false;
OutputStream outputStream;
final FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
// APPROACH #1: using retrieveFile(String, OutputStream)
for (final String leFichier : lesFichiers) {
outputStream = new BufferedOutputStream(new FileOutputStream(outputFolder + leFichier + suffix));
success = ftpClient.retrieveFile(inputFolder + leFichier, outputStream);
outputStream.close();
if (success) {
logger.info("Fichier " + leFichier + " copié correctement à partir du serveur.");
}
}
// APPROACH #2: using InputStream retrieveFileStream(String)
// final String remoteFile2 = "/test/song.mp3";
// final File downloadFile2 = new File("D:/Downloads/song.mp3");
// final OutputStream outputStream2 = new BufferedOutputStream(new
// FileOutputStream(downloadFile2));
// final InputStream inputStream =
// ftpClient.retrieveFileStream(remoteFile2);
// final byte[] bytesArray = new byte[4096];
// int bytesRead = -1;
// while ((bytesRead = inputStream.read(bytesArray)) != -1) {
// outputStream2.write(bytesArray, 0, bytesRead);
// }
//
// success = ftpClient.completePendingCommand();
//
// outputStream2.close();
// inputStream.close();
} catch (final IOException ex) {
logger.error("Error: ", ex.getMessage());
success = false;
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (final IOException ex) {
logger.error("Error: ", ex);
success = false;
}
}
return success;
}
}
public class UploadFileService {
private static final Logger logger = LogManager.getLogger(UploadFileService.class);
public static boolean uploadFile(final String url, final int port, final String username, final String password,
final String path, final String filename, final InputStream input) {
boolean success = false;
final FTPClient ftp = new FTPClient();
try {
int reply;
// on connecte le serveur ftp
ftp.connect(url, port);
ftp.login(username, password);
reply = ftp.getReplyCode();
// on verifie si la connexion est bon
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return success;
}
ftp.changeWorkingDirectory(path);
ftp.storeFile(filename, input);
input.close();
ftp.logout();
success = true;
logger.info("success de télécharger le fichier " + filename + " vers " + url);
} catch (final IOException e) {
logger.error("Error: " + e.getMessage());
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (final IOException ioe) {
logger.error("Error: " + ioe.getMessage());
}
}
}
return success;
}
}
public boolean uploadFileSFTP(final String host, final String username, final String password) throws SftpException {
boolean success = false;
Session session = null;
Channel channel = null;
try {
final JSch ssh = new JSch();
// ssh.setKnownHosts("src/test/resources/files/priv");
session = ssh.getSession(username, host, 22);
session.setPassword(password);
// TODO set no host key checking : just pour le test
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
channel = session.openChannel("sftp");
channel.connect();
final ChannelSftp sftp = (ChannelSftp) channel;
logger.info("Connexion SFTP sur " + host + " a ete etablir. ");
sftp.put("/path/of/local/file", "/path/of/ftp/file");
success = true;
} catch (final JSchException e) {
logger.error("Error: " + e.getMessage());
} finally {
if (channel != null) {
channel.disconnect();
}
if (session != null) {
session.disconnect();
}
}
return success;
}
@thiegoramos
Copy link

thiegoramos commented Oct 15, 2021

<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.55</version>
</dependency>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment