java 遠程ftp建立文件夾


  • import java.io.BufferedInputStream;  
  • import java.io.File;  
  • import java.io.FileInputStream;  
  • import java.io.FileNotFoundException;  
  • import java.io.IOException;  
  • import java.io.InputStream;  
  • import java.net.SocketException;  
  • import java.text.SimpleDateFormat;  
  • import java.util.Properties;  
  •   
  • import org.apache.commons.logging.Log;  
  • import org.apache.commons.net.ftp.FTP;  
  • import org.apache.commons.net.ftp.FTPClient;  
  • import org.apache.commons.net.ftp.FTPClientConfig;  
  • import org.apache.commons.net.ftp.FTPReply;  
  •   
  •   
  • /** 
  •  * 實現FTP 客戶端的各種操作 
  •  * 
  •  * 其實JDK里面也有支持FTP操作的包【jre/lib下的rt.jar】,但是SUN的DOC里面並沒有提供相應文檔, 
  •  * 因為這里面的包,不被官方支持,建議不要使用。我們可以使用第三方提供的包apache.commons。 apache.commons的包,都有文檔,方便使用 
  •  * 另外IBM也有提供一個ftp包,我沒有用過,有興趣的可以去研究一下 
  •  * 
  •  * @commons-net:http://apache.mirror.phpchina.com/commons/net/binaries/commons-net-1.4.1.zip 
  •  * @jakarta-oro:http://mirror.vmmatrix.net/apache/jakarta/oro/source/jakarta-oro-2.0.8.zip 
  •  * @commons-io:http://apache.mirror.phpchina.com/commons/io/binaries/commons-io-1.3.2-bin.zip 
  •  * 
  •  * @author  
  •  * @version 2008-06-10 Ftp.java 
  •  * 
  •  */  
  • public class Ftp {  
  •   
  •     private static Log logger;  
  •     /** 
  •      * FTP 登錄用戶名 
  •      */  
  •     private static String UserName;  
  •     /** 
  •      * FTP 登錄密碼 
  •      */  
  •     private static String Password;  
  •     /** 
  •      * FTP 服務器地址IP地址 
  •      */  
  •     private static String Ip;  
  •     /** 
  •      * FTP 端口 
  •      */  
  •     private static int Port;  
  •     /** 
  •      * 屬性集 
  •      */  
  •     private static Properties Property = null;  
  •     /** 
  •      * 配置文件的路徑名 
  •      */  
  •     private static String ConfigFile = "src/com/wwkj/cms/test/ftp/ftpconfig.properties";  
  •     /** 
  •      * FTP 客戶端代理 
  •      */  
  •     private static FTPClient FtpClient = null;  
  •     /** 
  •      * 時間格式化 
  •      */  
  •     private static SimpleDateFormat dateFormat = new SimpleDateFormat(  
  •             "yyyy-MM-dd hh:mm");  
  •     /** 
  •      * FTP 
  •      */  
  •     private static final String[] FILE_TYPES = { "文件", "目錄", "符號鏈接", "未知類型" };  
  •     /** 
  •      * 傳輸模式為二進制文件. 
  •      */  
  •     public static final int BINARY_FILE_TYPE = FTP.BINARY_FILE_TYPE;  
  •     /** 
  •      * 傳輸模式為ASCII,默認為ASCII 
  •      */  
  •     public static final int ASCII_FILE_TYPE = FTP.ASCII_FILE_TYPE;  
  •      public  static int  i=1;  
  •     public static void main(String[] args) {  
  •         // setConfigFile("ftpconfig.properties");// 設置配置文件路徑  
  •         connectServer();  
  •         // makeDirectory("eeee");  
  •   
  •         // changeWorkingDirectory("webroot");//進入文件夾webroot  
  •         // listRemoteFiles("*.jsp");//列出webroot目錄下所有jsp文件  
  •         setFileType(FTP.BINARY_FILE_TYPE);// 設置傳輸二進制文件  
  •   
  •         //uploadFile("G:/臨時文件/萬維公司員工交通通訊報銷標准(2008修訂版).doc",  
  •         //        "中國人也/萬維公司員工交通通訊報銷標准(2008修訂版).doc");//  
  •         // 上傳文件woxingwosu.xml,重新命名為myfile.xml  
  •         // renameFile("viewDetail.jsp",  
  •         // "newName.jsp");//將文件viewDetail.jsp改名為newName.jsp  
  • //        uploadManyFile("G:/臨時文件/staxmem", "dirdirdir/");  
  •         // deleteFile("/testtest/");//刪除一個文件UpdateData.class  
  •         // deleteEmptyDirectory("dfd");//  
  •         // loadFile("jakarta-oro-2.0.8.jar", "E:/tmp/00000000000000001.jpg");//  
  •   
  •         // 01.jpg,並且重新命名為G:/臨時文件/00000000000000001.jpg  
  •         // uploadFile("G:/臨時文件");  
  •   
  •         // listRemoteFiles("eeee");// 列出所有文件和目錄  
  •         // listRemoteFiles("58-20166.jpg");// 列出指定的文件和目錄  
  •         closeConnect();// 關閉連接  
  •     }  
  •   
  •     /** 
  •      * 上傳單個文件,並重命名 
  •      * 
  •      * @param localFilePath--本地文件路徑 
  •      * @param newFileName--新的文件名,可以命名為空"" 
  •      * @return true 上傳成功,false 上傳失敗 
  •      */  
  •     public static boolean uploadFile(String localFile, String newFileName) {  
  •         boolean flag = true;  
  •         try {  
  •   
  •             connectServer();  
  •             FtpClient.setFileType(BINARY_FILE_TYPE);  
  •             // ftp.setFileType(FTP.ASCII_FILE_TYPE);  
  •             FtpClient.enterLocalPassiveMode();  
  •             // ftp.changeWorkingDirectory(remoteDir);  
  •             FtpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);  
  •             File file = new File(localFile);  
  •   
  •             File newFile = new File(newFileName);  
  •             String dir = newFile.getParentFile().getPath();  
  •             if (!FtpClient.changeWorkingDirectory(dir)) {// 如果不能進入dir下,說明此目錄不存在!  
  •   
  •                 if (!makeDirectory(newFile.getParentFile().getPath())) {  
  •   
  •                     System.out.println("創建文件目錄【"+dir+"】 失敗!");  
  •                 }  
  •             }  
  •             changeWorkingDirectory("/");// 回到FTP根目錄  
  •             InputStream input = new FileInputStream(file);  
  •   
  •             if (input == null) {  
  •                 System.out.println("本地文件不存在");  
  •                 logger.debug("本地文件不存在,請重新選擇!");  
  •   
  •             }  
  •             if (newFileName.trim().equals("")) {  
  •   
  •                 newFileName = file.getName();  
  •   
  •             }  
  •             flag = FtpClient.storeFile(newFileName, input);  
  •             if (flag) {  
  •                 System.out.println("upload File succeed");  
  •   
  •             } else {  
  •                 System.out.println("upload File false");  
  •   
  •             }  
  •             input.close();  
  •   
  •         } catch (IOException e) {  
  •             e.printStackTrace();  
  •             logger.debug("本地文件上傳失敗!", e);  
  •             // TODO: handle exception  
  •         } catch (Exception e) {  
  •             e.printStackTrace();  
  •             // logger.debug("本地文件上傳失敗!", e);  
  •             // TODO: handle exception  
  •         }  
  •         return flag;  
  •     }  
  •   
  • //    /**  
  • //     * 上傳多個文件  
  • //     *  
  • //     * @param localFilePath--本地文件夾路徑  
  • //     * @return true 上傳成功,false 上傳失敗  
  • //     */  
  • //    public static String uploadManyFile(String localFile) {  
  • //        boolean flag = true;  
  • //        StringBuffer strBuf = new StringBuffer();  
  • //        int n = 0;  
  • //        try {  
  • //            connectServer();  
  • //            File file = new File(localFile);// 在此目錄中找文件  
  • //  
  • //            File file2[] = file.listFiles();  
  • //  
  • //            for (int i = 0; i < file2.length; i ) {  
  • //  
  • //                File file1 = new File(file2[i].getAbsolutePath());  
  • //                if (file1.isDirectory()) {// 文件夾中還有文件夾  
  • //                    uploadManyFile(file2[i].getAbsolutePath());  
  • //                } else {  
  • //                    flag = uploadFile(file2[i].getAbsolutePath(), "");  
  • //                }  
  • //                if (!flag) {  
  • //                    n ;  
  • //                    strBuf.append(file2[i].getName() "\r\n");  
  • //  
  • //                }  
  • //            }  
  • //            if (n > 0) {  
  • //  
  • //                strBuf.insert(0, "共有" n "上傳失敗,分別為\r\n");  
  • //            }  
  • //            System.out.println(strBuf.toString());  
  • //        } catch (NullPointerException e) {  
  • //            e.printStackTrace();  
  • //            // logger.debug("本地文件上傳失敗!找不到上傳文件!", e);  
  • //            // TODO: handle exception  
  • //        } catch (Exception e) {  
  • //            e.printStackTrace();  
  • //            logger.debug("本地文件上傳失敗!", e);  
  • //            // TODO: handle exception  
  • //        }  
  • //        return strBuf.toString();  
  • //    }  
  • //  
  • //    /**  
  • //     * 上傳多個文件  
  • //     *  
  • //     * @param localFilePath--本地文件夾路徑  
  • //     * @param newFileName--目標路徑  
  • //     * @return true 上傳成功,false 上傳失敗  
  • //     */  
  • //    public static String uploadManyFile(String localFile, String newFileName) {  
  • //        boolean flag = true;  
  • //        StringBuffer strBuf = new StringBuffer();  
  • //        int n = 0;  
  • //        try {  
  • //            connectServer();  
  • //            File file = new File(localFile);// 在此目錄中找文件  
  • //  
  • //            File file2[] = file.listFiles();  
  • //  
  • //            for (int i = 0; i < file2.length; i ) {  
  • //  
  • //                File file1 = new File(file2[i].getAbsolutePath());  
  • //                System.out.println(file1.isFile());  
  • //                if (file1.isDirectory()) {// 文件夾中還有文件夾  
  • //  
  • //                    uploadManyFile(file2[i].getAbsolutePath(), newFileName);  
  • //                } else {  
  • //                    String tmpNewFileName = "";  
  • //                    if (newFileName.substring(newFileName.length() - 1).equals(  
  • //                            "/")) {  
  • //  
  • //                        tmpNewFileName = newFileName file2[i].getName();  
  • //                    } else {  
  • //  
  • //                        tmpNewFileName = newFileName "/" file2[i].getName();  
  • //                    }  
  • //                    System.out.println(tmpNewFileName);  
  • //                    flag = uploadFile(file2[i].getAbsolutePath(),  
  • //                            tmpNewFileName);  
  • //                }  
  • //                if (!flag) {  
  • //                    n ;  
  • //                    strBuf.append(file2[i].getName() "\r\n");  
  • //  
  • //                }  
  • //            }  
  • //            if (n > 0) {  
  • //  
  • //                strBuf.insert(0, "共有" n "上傳失敗,分別為\r\n");  
  • //            }  
  • //            System.out.println(strBuf.toString());  
  • //        } catch (NullPointerException e) {  
  • //            e.printStackTrace();  
  • //            logger.debug("本地文件上傳失敗!找不到上傳文件!", e);  
  • //            // TODO: handle exception  
  • //        } catch (Exception e) {  
  • //            e.printStackTrace();  
  • //            logger.debug("本地文件上傳失敗!", e);  
  • //            // TODO: handle exception  
  • //        }  
  • //        return strBuf.toString();  
  • //    }  
  • //  
  • //    /**  
  • //     * 下載文件  
  • //     *  
  • //     * @param remoteFileName  
  • //     *            --服務器上的文件名  
  • //     * @param localFileName--本地文件名  
  • //     * @return true 下載成功,false 下載失敗  
  • //     *  
  • //     */  
  • //    public static boolean loadFile(String remoteFileName, String localFileName) {  
  • //        boolean flag = true;  
  • //        connectServer();  
  • //        // 下載文件  
  • //        BufferedOutputStream buffOut = null;  
  • //        try {  
  • //            buffOut = new BufferedOutputStream(new FileOutputStream(  
  • //                    localFileName));  
  • //            flag = FtpClient.retrieveFile(remoteFileName, buffOut);  
  • //        } catch (Exception e) {  
  • //            e.printStackTrace();  
  • //            logger.debug("本地文件下載失敗!", e);  
  • //        } finally {  
  • //            try {  
  • //                if (buffOut != null)  
  • //                    buffOut.close();  
  • //            } catch (Exception e) {  
  • //                e.printStackTrace();  
  • //  
  • //            }  
  • //        }  
  • //        return flag;  
  • //    }  
  • //  
  • //    /**  
  • //     * 刪除一個文件  
  • //     */  
  • //    public static boolean deleteFile(String filename) {  
  • //        boolean flag = true;  
  • //        try {  
  • //            connectServer();  
  • //  
  • //            flag = FtpClient.deleteFile(filename);  
  • //            if (flag) {  
  • //                System.out.println("delete  File succeed");  
  • //  
  • //            } else {  
  • //                System.out.println("delete File false");  
  • //  
  • //            }  
  • //        } catch (IOException ioe) {  
  • //            ioe.printStackTrace();  
  • //        }  
  • //        return flag;  
  • //    }  
  • //  
  • //    /**  
  • //     * 刪除目錄  
  • //     */  
  • //    public static void deleteDirectory(String pathname) {  
  • //        try {  
  • //            connectServer();  
  • //            File file = new File(pathname);  
  • //            if (file.isDirectory()) {  
  • //                File file2[] = file.listFiles();  
  • //            } else {  
  • //                deleteFile(pathname);  
  • //  
  • //            }  
  • //            FtpClient.removeDirectory(pathname);  
  • //        } catch (IOException ioe) {  
  • //            ioe.printStackTrace();  
  • //        }  
  • //    }  
  • //  
  • //    /**  
  • //     * 刪除空目錄  
  • //     */  
  • //    public static void deleteEmptyDirectory(String pathname) {  
  • //        try {  
  • //            connectServer();  
  • //            FtpClient.removeDirectory(pathname);  
  • //        } catch (IOException ioe) {  
  • //            ioe.printStackTrace();  
  • //        }  
  • //    }  
  •   
  • //    /**  
  • //     * 列出服務器上文件和目錄  
  • //     *  
  • //     * @param regStr  
  • //     *            --匹配的正則表達式  
  • //     */  
  • //    @SuppressWarnings("unchecked")  
  • //    public static void listRemoteFiles(String regStr) {  
  • //        connectServer();  
  • //        try {  
  • //            // FtpClient.changeWorkingDirectory(regStr);  
  • //            String files[] = FtpClient.listNames(regStr);  
  • //            if (files == null || files.length == 0)  
  • //                System.out.println("There has not any file!");  
  • //            else {  
  • //                for (int i = 0; i < files.length; i ) {  
  • //                    System.out.println(files[i]);  
  • //  
  • //                }  
  • //  
  • //            }  
  • //        } catch (Exception e) {  
  • //            e.printStackTrace();  
  • //        }  
  • //    }  
  • //  
  • //    /**  
  • //     * 列出Ftp服務器上的所有文件和目錄  
  • //     *  
  • //     */  
  • //    public static void listRemoteAllFiles() {  
  • //        connectServer();  
  • //        try {  
  • //            String[] names = FtpClient.listNames();  
  • //            for (int i = 0; i < names.length; i ) {  
  • //                System.out.println(names[i]);  
  • //            }  
  • //  
  • //        } catch (Exception e) {  
  • //            e.printStackTrace();  
  • //        }  
  • //    }  
  •   
  •     /** 
  •      * 關閉連接 
  •      */  
  •     public static void closeConnect() {  
  •         try {  
  •             if (FtpClient != null) {  
  •                 FtpClient.logout();  
  •                 FtpClient.disconnect();  
  •             }  
  •         } catch (Exception e) {  
  •             e.printStackTrace();  
  •         }  
  •     }  
  •   
  •     /** 
  •      * 設置配置文件 
  •      * 
  •      * @param configFile 
  •      */  
  •     public static void setConfigFile(String configFile) {  
  •         Ftp.ConfigFile = configFile;  
  •     }  
  •   
  •     /** 
  •      * 設置傳輸文件的類型[文本文件或者二進制文件] 
  •      * 
  •      * @param fileType--BINARY_FILE_TYPE、ASCII_FILE_TYPE 
  •      */  
  •     public static void setFileType(int fileType) {  
  •         try {  
  •             connectServer();  
  •             FtpClient.setFileType(fileType);  
  •         } catch (Exception e) {  
  •             e.printStackTrace();  
  •         }  
  •     }  
  •   
  •     /** 
  •      * 擴展使用 
  •      * 
  •      * @return 
  •      */  
  •     protected static FTPClient getFtpClient() {  
  •         connectServer();  
  •         return FtpClient;  
  •     }  
  •   
  •     /** 
  •      * 設置參數 
  •      * 
  •      * @param configFile 
  •      *            --參數的配置文件 
  •      */  
  •     private static void setArg(String configFile) {  
  •         Property = new Properties();  
  •         BufferedInputStream inBuff = null;  
  •         try {  
  •             File file = new File(configFile);  
  •   
  •             inBuff = new BufferedInputStream(new FileInputStream(file));  
  •   
  •             Property.load(inBuff);  
  •   
  •             UserName = Property.getProperty("username");  
  •             Password = Property.getProperty("password");  
  •             Ip = Property.getProperty("ip");  
  •             Port = Integer.parseInt(Property.getProperty("port"));  
  •         } catch (FileNotFoundException e1) {  
  •             System.out.println("配置文件 【" +configFile +"】不存在!");  
  •             e1.printStackTrace();  
  •         } catch (IOException e) {  
  •             System.out.println("配置文件 【" +configFile+ "】無法讀取!");  
  •             e.printStackTrace();  
  •         }  
  •   
  •         /* 
  •          * } catch (Exception e) { e.printStackTrace(); } finally { try { if 
  •          * (inBuff != null) inBuff.close(); } catch (Exception e) { 
  •          * e.printStackTrace(); } } 
  •          */  
  •     }  
  •   
  •     /** 
  •      * 連接到服務器 
  •      * 
  •      * @return true 連接服務器成功,false 連接服務器失敗 
  •      */  
  •     public static boolean connectServer() {  
  •         boolean flag = true;  
  •         if (FtpClient == null) {  
  •             int reply;  
  •             try {  
  •                 setArg(ConfigFile);  
  •                 FtpClient = new FTPClient();  
  •                 FtpClient.setControlEncoding("GBK");  
  •                 FtpClient.setDefaultPort(Port);  
  •                 FtpClient.configure(getFtpConfig());  
  •                 FtpClient.connect(Ip);  
  •                 FtpClient.login(UserName, Password);  
  •                 FtpClient.setDefaultPort(Port);  
  •                 //System.out.print(FtpClient.getReplyString());  
  •                 reply = FtpClient.getReplyCode();  
  •                 FtpClient.setDataTimeout(120000);  
  •   
  •                 if (!FTPReply.isPositiveCompletion(reply)) {  
  •                     FtpClient.disconnect();  
  •                     System.err.println("FTP server refused connection.");  
  •                     // logger.debug("FTP 服務拒絕連接!");  
  •                     flag = false;  
  •                 }  
  • //                System.out.println(i);  
  • //                i ;  
  •                  
  •             } catch (SocketException e) {  
  •                 flag = false;  
  •                 e.printStackTrace();  
  •                 System.err.println("登錄ftp服務器【" +Ip+ "】失敗,連接超時!");  
  •                 // logger.debug("登錄ftp服務器【" Ip "】失敗");  
  •             } catch (IOException e) {  
  •                 flag = false;  
  •   
  •                 e.printStackTrace();  
  •                 System.err.println("登錄ftp服務器【"+ Ip +"】失敗,FTP服務器無法打開!");  
  •                 // logger.debug("登錄ftp服務器【" Ip "】失敗");  
  •             }  
  •   
  •         }  
  •         return flag;  
  •     }  
  •   
  •     /** 
  •      * 進入到服務器的某個目錄下 
  •      * 
  •      * @param directory 
  •      */  
  •     public static void changeWorkingDirectory(String directory) {  
  •         try {  
  •             connectServer();  
  •             FtpClient.changeWorkingDirectory(directory);  
  •         } catch (IOException ioe) {  
  •             ioe.printStackTrace();  
  •         }  
  •     }  
  •   
  • //    /**  
  • //     * 返回到上一層目錄  
  • //     */  
  • //    public static void changeToParentDirectory() {  
  • //        try {  
  • //            connectServer();  
  • //            FtpClient.changeToParentDirectory();  
  • //        } catch (IOException ioe) {  
  • //            ioe.printStackTrace();  
  • //        }  
  • //    }  
  •   
  •     /** 
  •      * 重命名文件 
  •      * 
  •      * @param oldFileName 
  •      *            --原文件名 
  •      * @param newFileName 
  •      *            --新文件名 
  •      */  
  •     public static void renameFile(String oldFileName, String newFileName) {  
  •         try {  
  •             connectServer();  
  •             FtpClient.rename(oldFileName, newFileName);  
  •         } catch (IOException ioe) {  
  •             ioe.printStackTrace();  
  •         }  
  •     }  
  •   
  •     /** 
  •      * 設置FTP客服端的配置--一般可以不設置 
  •      * 
  •      * @return 
  •      */  
  •     private static FTPClientConfig getFtpConfig() {  
  •         FTPClientConfig ftpConfig = new FTPClientConfig(  
  •                 FTPClientConfig.SYST_UNIX);  
  •         ftpConfig.setServerLanguageCode(FTP.DEFAULT_CONTROL_ENCODING);  
  •         return ftpConfig;  
  •     }  
  •   
  •     /** 
  •      * 轉碼[ISO-8859-1 -> GBK] 不同的平台需要不同的轉碼 
  •      * 
  •      * @param obj 
  •      * @return 
  •      */  
  •     private static String iso8859togbk(Object obj) {  
  •         try {  
  •             if (obj == null)  
  •                 return "";  
  •             else  
  •                 return new String(obj.toString().getBytes("iso-8859-1"), "GBK");  
  •         } catch (Exception e) {  
  •             return "";  
  •         }  
  •     }  
  •   
  •     /** 
  •      * 在服務器上創建一個文件夾 
  •      * 
  •      * @param dir 
  •      *            文件夾名稱,不能含有特殊字符,如 \ 、/ 、: 、* 、?、 "、 <、>... 
  •      */  
  •     public static boolean makeDirectory(String dir) {  
  •         connectServer();  
  •         boolean flag = true;  
  •         try {  
  •             // System.out.println("dir=======" dir);  
  •             flag = FtpClient.makeDirectory(dir);  
  •             if (flag) {  
  •                 System.out.println("make Directory " +dir +" succeed");  
  •   
  •             } else {  
  •   
  •                 System.out.println("make Directory " +dir+ " false");  
  •             }  
  •         } catch (Exception e) {  
  •             e.printStackTrace();  
  •         }  
  •         return flag;  
  •     }  
  •   
  •     public static Log getLogger() {  
  •         return logger;  
  •     }  
  •   
  •     public static void setLogger(Log logger) {  
  •         Ftp.logger = logger;  
  •     }  
  •   

  • 免責聲明!

    本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



     
    粵ICP備18138465號   © 2018-2025 CODEPRJ.COM