Upload via SFTP in Java

1) Add Maven dependency

1
2
3
4
5
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.42</version>
</dependency>

2) Java code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import java.io.File;
import java.io.FileInputStream;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class TestJSftp {
public static void upload(String username,
String password,
String host,
int port,
String workingDir,
String localFilename){
try {
JSch jsch = new JSch();
Session session = jsch.getSession(username, host, port);
session.setPassword(password);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp channelSftp = (ChannelSftp) channel;
channelSftp.cd(workingDir);
File f1 = new File(localFilename);
channelSftp.put(new FileInputStream(f1), f1.getName(), ChannelSftp.OVERWRITE);
channelSftp.exit();
session.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Share