1. 依赖
<!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-net/commons-net -->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>
2. FTPUtil
package others;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import org.apache.commons.net.ftp.*;
import java.io.*;
import java.util.Properties;
public class FTPUtil {
private static ChannelSftp sftp = null;
public static boolean uploadFile(String host, int port, String username, String password, String basePath, String filename, InputStream input) {
boolean result = false;
FTPClient ftp = new FTPClient();
File file = null;
try {
JSch jsch = new JSch();
Session sshSession = jsch.getSession(username, host, port);
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig("kex", "diffie-hellman-group1-sha1");
sshSession.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
sshSession.setConfig(sshConfig);
sshSession.connect();
Channel channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
file = new File(basePath);
sftp.cd(basePath);
sftp.put(input, filename);
input.close();
result = true;
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return result;
}
public static void main(String[] args) throws FileNotFoundException {
InputStream input = new FileInputStream("D:\\药企.txt");
String newName = "药企";
boolean t = uploadFile("192.168.72.153", 22, "root", "473791", "/usr/local/src/mysql", newName,
input);
System.out.println("t = " + t);
}
}