-
-
Save Sammy30/5da632ee3a5ccd9cb250f020d11f620b to your computer and use it in GitHub Desktop.
Jsch sftp sample
This file contains 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
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