900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > 工具类篇-07-往Linux服务器上传文件工具类

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

时间:2020-07-13 22:02:07

相关推荐

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

文章目录

1. 依赖2. FTPUtil

1. 依赖

<!-- /artifact/com.jcraft/jsch --><dependency><groupId>com.jcraft</groupId><artifactId>jsch</artifactId><version>0.1.54</version></dependency><!-- /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 .ftp.*;import java.io.*;import java.util.Properties;/*** 向FTP服务器上传文件*/public class FTPUtil {private static ChannelSftp sftp = null;/*** Description: 向FTP服务器上传文件** @param hostFTP服务器ip* @param portFTP服务器端口* @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);}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。