java ftp上传文件 工具类
package com.learning.spboot.utils; import com.jcraft.jsch.*; import org.apache.commons.net.ftp.FTPClient; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Properties; import java.util.Vector; public class FTPUtils { //远程服务器地址 private final static String homeName = "47.104.99.125"; //ftp端口 private final static int homePort = 22; private final static String userename = "****"; private final static String password = "*****"; public static String init(String dirPaht,String filepath) { ChannelSftp sftp = null; Channel channel = null; Session sshSession = null; JSch jscj=new JSch(); try { jscj.getSession(userename,homeName,homePort); sshSession=jscj.getSession(userename,homeName,homePort); sshSession.setPassword(password); Properties sshConfig = new Properties(); sshConfig.put("StrictHostKeyChecking", "no"); sshSession.setConfig(sshConfig); sshSession.connect(); if(sshSession.isConnected()) { System.out.println("连接成功!"); System.out.println("Session connected!"); /*sftp.setFilenameEncoding("UTF-8"); sftp.*/ channel = sshSession.openChannel("sftp"); channel.connect(); sftp = (ChannelSftp) channel; //判断当前上传路径是否存在 try { Vector <?> vector = sftp.ls(dirPaht);//首次路径不存在,会报错 if (vector == null) { //sftp.rmdir(dirPaht); sftp.mkdir(dirPaht); } }catch (Exception e){ e.getMessage(); sftp.mkdir(dirPaht);//创建上传路径 } //切换到目录上传目录下 sftp.cd(dirPaht); File file=new File(filepath); String filetype=file.getName().substring(file.getName().lastIndexOf(".")+1); String newFileName= new SimpleDateFormat("yyyymmdd").format(new Date())+"."+filetype; InputStream ins = new FileInputStream(file); //中文名称的 sftp.put(ins, new String(newFileName.getBytes(),"UTF-8")); } else { System.out.println("连接失败!"); } } catch (Exception e) { e.printStackTrace(); } return null; } public static void main(String []args ){ new FTPUtils().init("/java/image/","D:\\开发工具软件\\ideaImg\\011.jpg"); } }