標籤:判斷 dir path form str ima type col .text
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"); }}
java ftp上傳檔案 工具類