文章目录
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);}
}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!