Skip to content

Instantly share code, notes, and snippets.

@Sammy30
Forked from goyuninfo/jsch-sftp-example.java
Last active July 5, 2022 02:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sammy30/5da632ee3a5ccd9cb250f020d11f620b to your computer and use it in GitHub Desktop.
Save Sammy30/5da632ee3a5ccd9cb250f020d11f620b to your computer and use it in GitHub Desktop.
Jsch sftp sample
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
*
* @author it.i88.ca
*/
public class NewClass {
public static void main(String[] args) {
String SFTPHOST = "192.168.3.70";
int SFTPPORT = 22;
String SFTPUSER = "user";
String SFTPPASS = "passwd";
String SFTPWORKINGDIR = "test";
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
try {
JSch jsch = new JSch();
session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
session.setPassword(SFTPPASS);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
int timeOutMilliseconds = 60000;
session.connect(timeOutMilliseconds);
channel = session.openChannel("sftp");
channel.connect();
channelSftp = (ChannelSftp) channel;
channelSftp.cd(SFTPWORKINGDIR);
byte[] buffer = new byte[1024];
BufferedInputStream bis = new BufferedInputStream(channelSftp.get("test.txt"));
File newFile = new File("test.i88.ca.txt");
OutputStream os = new FileOutputStream(newFile);
BufferedOutputStream bos = new BufferedOutputStream(os);
int readCount;
while ((readCount = bis.read(buffer)) > 0) {
bos.write(buffer, 0, readCount);
}
bis.close();
bos.close();
channel.disconnect();
session.disconnect();
//return;
} catch (JSchException | SftpException | IOException ex) {
ex.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment