工具类篇-07-往Linux服务器上传文件工具类

文章目录

  • 1. 依赖
  • 2. FTPUtil

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;/*** 向FTP服务器上传文件*/
public class FTPUtil {private static ChannelSftp sftp = null;/*** Description: 向FTP服务器上传文件** @param host     FTP服务器ip* @param port     FTP服务器端口* @param username FTP登录账号* @param password FTP登录密码* @param basePath FTP服务器基础目录,/home/ftpuser/images* @param filename 上传到FTP服务器上的文件名* @param input    输入流* @return 成功返回true,否则返回false*/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();//获取sshSession  账号-ip-端口Session sshSession = jsch.getSession(username, host, port);//添加密码sshSession.setPassword(password);Properties sshConfig = new Properties();//严格主机密钥检查sshConfig.put("StrictHostKeyChecking", "no");//设置ssh的DH秘钥交换sshSession.setConfig("kex", "diffie-hellman-group1-sha1");//跳过Kerberos username 身份验证提示sshSession.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
//            sshConfig.put("PreferredAuthentications","publickey,keyboard-interactive,password");sshSession.setConfig(sshConfig);//开启sshSession链接sshSession.connect();//获取sftp通道Channel channel = sshSession.openChannel("sftp");//开启channel.connect();sftp = (ChannelSftp) channel;file = new File(basePath);//设置为被动模式
//            ftp.enterLocalPassiveMode();//设置上传文件的类型为二进制类型//进入到要上传的目录  然后上传文件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);}
}


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

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部