import java.io.BufferedReader;java import java.io.File;spring import java.io.FileInputStream;apache import java.io.FileOutputStream;服務器 import java.io.IOException;svn import java.io.InputStreamReader;url import org.apache.log4j.Logger;spa import com.zhiwei.core.util.AppUtil;.net import java.net.InetSocketAddress;server import java.net.SocketAddress; xml import sun.net.TelnetInputStream; import sun.net.TelnetOutputStream; import sun.net.ftp.FtpClient; import sun.net.ftp.FtpProtocolException; public class FtpUtils { protected static Logger LOG=Logger.getLogger(FtpUtils.class); private FtpClient ftpClient=null;
/** * 鏈接ftp服務器 JDK 1.7 * * @param url * @param port * @param username * @param password * @return FtpClient * @throws FtpProtocolException * @throws IOException */ public FtpClient connect(String url, int port, String username, String password) { // 建立ftp try { // 建立地址 SocketAddress addr = new InetSocketAddress(url, port); // 鏈接 ftpClient = FtpClient.create(); ftpClient.setConnectTimeout(6000000); ftpClient.connect(addr); // 登錄 ftpClient.login(username, password.toCharArray()); ftpClient.setBinaryType();
System.out.println("------------------------------ftp服務器已鏈接----------------------"); } catch (FtpProtocolException e) { LOG.error("ftp鏈接服務器出錯,出錯緣由\r\n", e); } catch (IOException e) { LOG.error("ftp鏈接服務器出錯,出錯緣由", e); } return ftpClient; }
/** * 切換目錄 * * @param ftp * @param path */ public void cd(String path) { try { ftpClient.changeDirectory(path); LOG.info("切換目錄"+ftpClient.getWorkingDirectory()); // System.out.println(ftpClient.getWorkingDirectory()); } catch (FtpProtocolException e) { LOG.error("切換目錄出錯",e); } catch (IOException e) { LOG.error("切換目錄出錯",e); } }
//上傳建立的文件夾或文件 public void uploadDirectory(String directory,boolean bl,String nameFtp,String n,String serverIp,String username,String password)throws IOException, FtpProtocolException{ if (ftpClient==null) { Integer ss = Integer.valueOf(n); connect(serverIp, ss,username , password); } File file=new File(directory); String name=null;//待上傳文件名 boolean result; if(file.isDirectory()){ String dir = file.getName(); if(bl){ dir = nameFtp; bl = false; } result=isDirExist(ftpClient,dir); if (!result) { LOG.error(dir+"----------該文件夾已存在"); } try { ftpClient.changeDirectory(dir); ftpClient.setBinaryType(); } catch (FtpProtocolException e) { LOG.error("------進入"+dir+"文件夾失敗--------",e); } String[] files = file.list(); for (int i = 0; i < files.length; i++) { File tmpFile = new File(file.getPath()+"\\"+files[i] ); if(tmpFile.isDirectory()){ uploadDirectory(tmpFile.getAbsolutePath(),bl,nameFtp, n, serverIp, username, password); }else{ name=tmpFile.getName(); upload(directory+"/"+name, n, serverIp, username, password); } } ftpClient.changeToParentDirectory(); }else{ //文件上傳 upload(directory,file.getName(), n, serverIp, username, password); } } //文件上傳 public void upload(String srcFile,String n,String serverIp,String username,String password)throws IOException{
File file=new File(srcFile); FileInputStream fin=new FileInputStream(srcFile);
TelnetOutputStream tos = null; try { tos = (TelnetOutputStream) ftpClient.putFileStream(file.getName(), true); if(file.getName().equals("spring.xml")){ InputStreamReader ie=new InputStreamReader(fin, "utf-8"); BufferedReader reader = new BufferedReader(ie); String line = null; while ((line = reader.readLine()) != null) { if(line.indexOf("serverIp")!=-1){ line=line.replaceAll("serverIp", serverIp); line=line.replaceAll("dataName", n); } if(line.indexOf("datausername")!=-1){ line=line.replaceAll("datausername", username); } if(line.indexOf("datapassword")!=-1){ line=line.replaceAll("datapassword", password); } tos.write(line.getBytes("utf-8")); } reader.close(); ie.close(); }else{ int readLength = 0; byte[] buf = new byte[1024]; while ( (readLength = fin.read(buf)) != -1) { tos.write(buf, 0, readLength); } } fin.close(); tos.close(); } catch (Exception e) { //System.out.println("--------獲取遠程文件輸出流失敗---"); LOG.error("--------獲取遠程文件輸出流失敗---",e ); } } public void upload(String srcFile,String destFile,String n,String serverIp,String username,String password)throws IOException{ upload(srcFile, n, serverIp, username, password); File file=new File(srcFile); //文件重命名 打開 上傳 zip文件會報錯 先關閉 // ftpClient.rename(file.getName(), destFile); } public void close(){ try { ftpClient.close(); } catch (IOException e) { LOG.error("關閉輸出流失敗",e); } } /** * @param directory 上傳文件在服務器上的存放路徑 * @param srcFilePath 要上傳文件的存放路徑 * svn:songwj * 建立文件夾、調用上傳方法進行上傳 * @throws FtpProtocolException */ public void swjUploadDirectory(String directory,String srcFilePath,boolean bl,String nameFtp,String n,String serverIp,String username,String password,String dirStr)throws IOException, FtpProtocolException{
System.out.println("服務器上要建立文件夾路徑-------------"+dirStr); boolean result; //1 建立各個節點的文件夾 if(!"".equals(dirStr)){ String dir =dirStr; String url[] = dir.split("/"); for(int i = 0;i<url.length;i++){ try { result=isDirExist(ftpClient,url[i]); if (result) { LOG.info("建立"+url[i]+"成功"); }else { LOG.info(url[i]+"已存在"); } ftpClient.changeDirectory(url[i]); ftpClient.setBinaryType(); } catch (FtpProtocolException e) { LOG.error("------建立文件夾失敗-----", e); } } } //2 調用上傳方法上傳文件 swjUpload(srcFilePath,directory, n, serverIp, username, password); }
/** 判斷Ftp目錄是否存在 * @throws FtpProtocolException */ public boolean isDirExist(FtpClient ftpClient, String dir) { try{ ftpClient.makeDirectory(dir); } catch (FtpProtocolException e1){ return false; }catch (IOException e) { return false; } return true; }
/** * 文件上傳代碼 * @param srcFile 要上傳文件的路徑 * @param fileToServerPath 上傳文件存放在服務器上的位置 * @param n * @param serverIp * @param username * @param password * @throws IOException */ public void swjUpload(String srcFile,String fileToServerPath,String n,String serverIp,String username,String password)throws IOException{
//建立一個文件(服務器上對應的文件) File serverFile = new File(fileToServerPath);
//建立選擇要上傳的文件對象 File srFile=new File(srcFile);
//把上傳的文件對象放入文件流中 FileInputStream fin=new FileInputStream(srcFile); LOG.info("上傳到服務器地址==="+fileToServerPath); //System.out.println("fileToServerPath==="+fileToServerPath); //打開ftp上的文件 準備接收 TelnetOutputStream tos = null; try { tos = (TelnetOutputStream) ftpClient.putFileStream(serverFile.getName(), true); if(srFile.getName().equals("spring.xml")){ InputStreamReader ie=new InputStreamReader(fin, "utf-8"); BufferedReader reader = new BufferedReader(ie);//讀取要上傳的 文件 String line = null; while ((line = reader.readLine()) != null) { if(line.indexOf("serverIp")!=-1){ line=line.replaceAll("serverIp", serverIp); line=line.replaceAll("dataName", n); } if(line.indexOf("datausername")!=-1){ line=line.replaceAll("datausername", username); } if(line.indexOf("datapassword")!=-1){ line=line.replaceAll("datapassword", password); } tos.write(line.getBytes("utf-8")); } reader.close(); ie.close(); }else{ int readLength = 0; byte[] buf = new byte[1024]; while ( (readLength = fin.read(buf)) != -1) { tos.write(buf, 0, readLength);//把要上傳文件流寫入服務器的文件中 } } tos.close(); } catch (Exception e) { LOG.error("上傳文件到服務器失敗", e); } fin.close(); }
/** * Ftp 服務器文件下載單個文件 * svn:songwj * @param srcStr 要下載文件的路徑 * @param disStr 下載文件存放的路徑 */ public void ftpDownFile(String srcStr,String disStr) {
// 讀取配置文件讀取ftp ip地址 端口號 帳戶 密碼 String ip = AppUtil.getFtpIp(); String us = AppUtil.getFtpUsName();//賬號 String ps = AppUtil.getFtpPss();//密碼 int port = Integer.valueOf(AppUtil.getFtpPort());//端口 默認爲 21 connect(ip, port, us, ps); TelnetInputStream is = null; FileOutputStream os = null;
System.out.println("srcStr--------------------"+srcStr); System.out.println("disStr--------------------"+disStr);
try { //獲取遠程機器上的文件filename,藉助TelnetInputStream把該文件傳送到本地。 ftpClient.changeDirectory(srcStr); is = (TelnetInputStream) ftpClient.getFileStream(srcStr);
System.out.println("os--------------------"+os.toString());
byte[] bytes = new byte[2048]; int c; while ((c = is.read(bytes)) != -1) { os.write(bytes, 0, c); } System.out.println("----------------下載成功----------------"); } catch (IOException ex) { //System.out.println("下載失敗"); LOG.error("---------------下載失敗--------------", ex); throw new RuntimeException(ex); } catch (FtpProtocolException e) { LOG.error("----------------下載失敗----------------", e); } finally{ try { if(is != null){ is.close(); } } catch (IOException e) { e.printStackTrace(); } finally { try { if(os != null){ os.close(); } } catch (IOException e) { e.printStackTrace(); } } } } /** * 刪除ftp服務器上指定的文件 * @param fileName */ public String removeFile(String deleteFilePath){
System.out.println("---------進入到刪除方法中"); String resultStr = "";
if(ftpClient!= null){ try {
ftpClient.deleteFile(deleteFilePath); //ftpClient.deleteFile("D:/sendMessagePicture.png"); //ftpClient.deleteFile( "D:\\sendMessagePicture.png"); resultStr = ftpClient.getLastResponseString(); //FtpReplyCode lastReplyCode = ftpClient.getLastReplyCode(); System.out.println("status----------------"+resultStr); } catch (Exception e) { LOG.error("刪除失敗", e); } }else{ resultStr = "FAIL"; } return resultStr; } } |