java 远程ftp建立文件夹

  1. import java.io.BufferedInputStream;  
  2. import java.io.File;  
  3. import java.io.FileInputStream;  
  4. import java.io.FileNotFoundException;  
  5. import java.io.IOException;  
  6. import java.io.InputStream;  
  7. import java.net.SocketException;  
  8. import java.text.SimpleDateFormat;  
  9. import java.util.Properties;  
  10.   
  11. import org.apache.commons.logging.Log;  
  12. import org.apache.commons.net.ftp.FTP;  
  13. import org.apache.commons.net.ftp.FTPClient;  
  14. import org.apache.commons.net.ftp.FTPClientConfig;  
  15. import org.apache.commons.net.ftp.FTPReply;  
  16.   
  17.   
  18. /** 
  19.  * 实现FTP 客户端的各种操作 
  20.  * 
  21.  * 其实JDK里面也有支持FTP操作的包【jre/lib下的rt.jar】,但是SUN的DOC里面并没有提供相应文档, 
  22.  * 因为这里面的包,不被官方支持,建议不要使用。我们可以使用第三方提供的包apache.commons。 apache.commons的包,都有文档,方便使用 
  23.  * 另外IBM也有提供一个ftp包,我没有用过,有兴趣的可以去研究一下 
  24.  * 
  25.  * @commons-net:http://apache.mirror.phpchina.com/commons/net/binaries/commons-net-1.4.1.zip 
  26.  * @jakarta-oro:http://mirror.vmmatrix.net/apache/jakarta/oro/source/jakarta-oro-2.0.8.zip 
  27.  * @commons-io:http://apache.mirror.phpchina.com/commons/io/binaries/commons-io-1.3.2-bin.zip 
  28.  * 
  29.  * @author  
  30.  * @version 2008-06-10 Ftp.java 
  31.  * 
  32.  */  
  33. public class Ftp {  
  34.   
  35.     private static Log logger;  
  36.     /** 
  37.      * FTP 登录用户名 
  38.      */  
  39.     private static String UserName;  
  40.     /** 
  41.      * FTP 登录密码 
  42.      */  
  43.     private static String Password;  
  44.     /** 
  45.      * FTP 服务器地址IP地址 
  46.      */  
  47.     private static String Ip;  
  48.     /** 
  49.      * FTP 端口 
  50.      */  
  51.     private static int Port;  
  52.     /** 
  53.      * 属性集 
  54.      */  
  55.     private static Properties Property = null;  
  56.     /** 
  57.      * 配置文件的路径名 
  58.      */  
  59.     private static String ConfigFile = "src/com/wwkj/cms/test/ftp/ftpconfig.properties";  
  60.     /** 
  61.      * FTP 客户端代理 
  62.      */  
  63.     private static FTPClient FtpClient = null;  
  64.     /** 
  65.      * 时间格式化 
  66.      */  
  67.     private static SimpleDateFormat dateFormat = new SimpleDateFormat(  
  68.             "yyyy-MM-dd hh:mm");  
  69.     /** 
  70.      * FTP 
  71.      */  
  72.     private static final String[] FILE_TYPES = { "文件", "目录", "符号链接", "未知类型" };  
  73.     /** 
  74.      * 传输模式为二进制文件. 
  75.      */  
  76.     public static final int BINARY_FILE_TYPE = FTP.BINARY_FILE_TYPE;  
  77.     /** 
  78.      * 传输模式为ASCII,默认为ASCII 
  79.      */  
  80.     public static final int ASCII_FILE_TYPE = FTP.ASCII_FILE_TYPE;  
  81.      public  static int  i=1;  
  82.     public static void main(String[] args) {  
  83.         // setConfigFile("ftpconfig.properties");// 设置配置文件路径  
  84.         connectServer();  
  85.         // makeDirectory("eeee");  
  86.   
  87.         // changeWorkingDirectory("webroot");//进入文件夹webroot  
  88.         // listRemoteFiles("*.jsp");//列出webroot目录下所有jsp文件  
  89.         setFileType(FTP.BINARY_FILE_TYPE);// 设置传输二进制文件  
  90.   
  91.         //uploadFile("G:/临时文件/万维公司员工交通通讯报销标准(2008修订版).doc",  
  92.         //        "中国人也/万维公司员工交通通讯报销标准(2008修订版).doc");//  
  93.         // 上传文件woxingwosu.xml,重新命名为myfile.xml  
  94.         // renameFile("viewDetail.jsp",  
  95.         // "newName.jsp");//将文件viewDetail.jsp改名为newName.jsp  
  96. //        uploadManyFile("G:/临时文件/staxmem", "dirdirdir/");  
  97.         // deleteFile("/testtest/");//删除一个文件UpdateData.class  
  98.         // deleteEmptyDirectory("dfd");//  
  99.         // loadFile("jakarta-oro-2.0.8.jar", "E:/tmp/00000000000000001.jpg");//  
  100.   
  101.         // 01.jpg,并且重新命名为G:/临时文件/00000000000000001.jpg  
  102.         // uploadFile("G:/临时文件");  
  103.   
  104.         // listRemoteFiles("eeee");// 列出所有文件和目录  
  105.         // listRemoteFiles("58-20166.jpg");// 列出指定的文件和目录  
  106.         closeConnect();// 关闭连接  
  107.     }  
  108.   
  109.     /** 
  110.      * 上传单个文件,并重命名 
  111.      * 
  112.      * @param localFilePath--本地文件路径 
  113.      * @param newFileName--新的文件名,可以命名为空"" 
  114.      * @return true 上传成功,false 上传失败 
  115.      */  
  116.     public static boolean uploadFile(String localFile, String newFileName) {  
  117.         boolean flag = true;  
  118.         try {  
  119.   
  120.             connectServer();  
  121.             FtpClient.setFileType(BINARY_FILE_TYPE);  
  122.             // ftp.setFileType(FTP.ASCII_FILE_TYPE);  
  123.             FtpClient.enterLocalPassiveMode();  
  124.             // ftp.changeWorkingDirectory(remoteDir);  
  125.             FtpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);  
  126.             File file = new File(localFile);  
  127.   
  128.             File newFile = new File(newFileName);  
  129.             String dir = newFile.getParentFile().getPath();  
  130.             if (!FtpClient.changeWorkingDirectory(dir)) {// 如果不能进入dir下,说明此目录不存在!  
  131.   
  132.                 if (!makeDirectory(newFile.getParentFile().getPath())) {  
  133.   
  134.                     System.out.println("创建文件目录【"+dir+"】 失败!");  
  135.                 }  
  136.             }  
  137.             changeWorkingDirectory("/");// 回到FTP根目录  
  138.             InputStream input = new FileInputStream(file);  
  139.   
  140.             if (input == null) {  
  141.                 System.out.println("本地文件不存在");  
  142.                 logger.debug("本地文件不存在,请重新选择!");  
  143.   
  144.             }  
  145.             if (newFileName.trim().equals("")) {  
  146.   
  147.                 newFileName = file.getName();  
  148.   
  149.             }  
  150.             flag = FtpClient.storeFile(newFileName, input);  
  151.             if (flag) {  
  152.                 System.out.println("upload File succeed");  
  153.   
  154.             } else {  
  155.                 System.out.println("upload File false");  
  156.   
  157.             }  
  158.             input.close();  
  159.   
  160.         } catch (IOException e) {  
  161.             e.printStackTrace();  
  162.             logger.debug("本地文件上传失败!", e);  
  163.             // TODO: handle exception  
  164.         } catch (Exception e) {  
  165.             e.printStackTrace();  
  166.             // logger.debug("本地文件上传失败!", e);  
  167.             // TODO: handle exception  
  168.         }  
  169.         return flag;  
  170.     }  
  171.   
  172. //    /**  
  173. //     * 上传多个文件  
  174. //     *  
  175. //     * @param localFilePath--本地文件夹路径  
  176. //     * @return true 上传成功,false 上传失败  
  177. //     */  
  178. //    public static String uploadManyFile(String localFile) {  
  179. //        boolean flag = true;  
  180. //        StringBuffer strBuf = new StringBuffer();  
  181. //        int n = 0;  
  182. //        try {  
  183. //            connectServer();  
  184. //            File file = new File(localFile);// 在此目录中找文件  
  185. //  
  186. //            File file2[] = file.listFiles();  
  187. //  
  188. //            for (int i = 0; i < file2.length; i ) {  
  189. //  
  190. //                File file1 = new File(file2[i].getAbsolutePath());  
  191. //                if (file1.isDirectory()) {// 文件夹中还有文件夹  
  192. //                    uploadManyFile(file2[i].getAbsolutePath());  
  193. //                } else {  
  194. //                    flag = uploadFile(file2[i].getAbsolutePath(), "");  
  195. //                }  
  196. //                if (!flag) {  
  197. //                    n ;  
  198. //                    strBuf.append(file2[i].getName() "\r\n");  
  199. //  
  200. //                }  
  201. //            }  
  202. //            if (n > 0) {  
  203. //  
  204. //                strBuf.insert(0, "共有" n "上传失败,分别为\r\n");  
  205. //            }  
  206. //            System.out.println(strBuf.toString());  
  207. //        } catch (NullPointerException e) {  
  208. //            e.printStackTrace();  
  209. //            // logger.debug("本地文件上传失败!找不到上传文件!", e);  
  210. //            // TODO: handle exception  
  211. //        } catch (Exception e) {  
  212. //            e.printStackTrace();  
  213. //            logger.debug("本地文件上传失败!", e);  
  214. //            // TODO: handle exception  
  215. //        }  
  216. //        return strBuf.toString();  
  217. //    }  
  218. //  
  219. //    /**  
  220. //     * 上传多个文件  
  221. //     *  
  222. //     * @param localFilePath--本地文件夹路径  
  223. //     * @param newFileName--目标路径  
  224. //     * @return true 上传成功,false 上传失败  
  225. //     */  
  226. //    public static String uploadManyFile(String localFile, String newFileName) {  
  227. //        boolean flag = true;  
  228. //        StringBuffer strBuf = new StringBuffer();  
  229. //        int n = 0;  
  230. //        try {  
  231. //            connectServer();  
  232. //            File file = new File(localFile);// 在此目录中找文件  
  233. //  
  234. //            File file2[] = file.listFiles();  
  235. //  
  236. //            for (int i = 0; i < file2.length; i ) {  
  237. //  
  238. //                File file1 = new File(file2[i].getAbsolutePath());  
  239. //                System.out.println(file1.isFile());  
  240. //                if (file1.isDirectory()) {// 文件夹中还有文件夹  
  241. //  
  242. //                    uploadManyFile(file2[i].getAbsolutePath(), newFileName);  
  243. //                } else {  
  244. //                    String tmpNewFileName = "";  
  245. //                    if (newFileName.substring(newFileName.length() - 1).equals(  
  246. //                            "/")) {  
  247. //  
  248. //                        tmpNewFileName = newFileName file2[i].getName();  
  249. //                    } else {  
  250. //  
  251. //                        tmpNewFileName = newFileName "/" file2[i].getName();  
  252. //                    }  
  253. //                    System.out.println(tmpNewFileName);  
  254. //                    flag = uploadFile(file2[i].getAbsolutePath(),  
  255. //                            tmpNewFileName);  
  256. //                }  
  257. //                if (!flag) {  
  258. //                    n ;  
  259. //                    strBuf.append(file2[i].getName() "\r\n");  
  260. //  
  261. //                }  
  262. //            }  
  263. //            if (n > 0) {  
  264. //  
  265. //                strBuf.insert(0, "共有" n "上传失败,分别为\r\n");  
  266. //            }  
  267. //            System.out.println(strBuf.toString());  
  268. //        } catch (NullPointerException e) {  
  269. //            e.printStackTrace();  
  270. //            logger.debug("本地文件上传失败!找不到上传文件!", e);  
  271. //            // TODO: handle exception  
  272. //        } catch (Exception e) {  
  273. //            e.printStackTrace();  
  274. //            logger.debug("本地文件上传失败!", e);  
  275. //            // TODO: handle exception  
  276. //        }  
  277. //        return strBuf.toString();  
  278. //    }  
  279. //  
  280. //    /**  
  281. //     * 下载文件  
  282. //     *  
  283. //     * @param remoteFileName  
  284. //     *            --服务器上的文件名  
  285. //     * @param localFileName--本地文件名  
  286. //     * @return true 下载成功,false 下载失败  
  287. //     *  
  288. //     */  
  289. //    public static boolean loadFile(String remoteFileName, String localFileName) {  
  290. //        boolean flag = true;  
  291. //        connectServer();  
  292. //        // 下载文件  
  293. //        BufferedOutputStream buffOut = null;  
  294. //        try {  
  295. //            buffOut = new BufferedOutputStream(new FileOutputStream(  
  296. //                    localFileName));  
  297. //            flag = FtpClient.retrieveFile(remoteFileName, buffOut);  
  298. //        } catch (Exception e) {  
  299. //            e.printStackTrace();  
  300. //            logger.debug("本地文件下载失败!", e);  
  301. //        } finally {  
  302. //            try {  
  303. //                if (buffOut != null)  
  304. //                    buffOut.close();  
  305. //            } catch (Exception e) {  
  306. //                e.printStackTrace();  
  307. //  
  308. //            }  
  309. //        }  
  310. //        return flag;  
  311. //    }  
  312. //  
  313. //    /**  
  314. //     * 删除一个文件  
  315. //     */  
  316. //    public static boolean deleteFile(String filename) {  
  317. //        boolean flag = true;  
  318. //        try {  
  319. //            connectServer();  
  320. //  
  321. //            flag = FtpClient.deleteFile(filename);  
  322. //            if (flag) {  
  323. //                System.out.println("delete  File succeed");  
  324. //  
  325. //            } else {  
  326. //                System.out.println("delete File false");  
  327. //  
  328. //            }  
  329. //        } catch (IOException ioe) {  
  330. //            ioe.printStackTrace();  
  331. //        }  
  332. //        return flag;  
  333. //    }  
  334. //  
  335. //    /**  
  336. //     * 删除目录  
  337. //     */  
  338. //    public static void deleteDirectory(String pathname) {  
  339. //        try {  
  340. //            connectServer();  
  341. //            File file = new File(pathname);  
  342. //            if (file.isDirectory()) {  
  343. //                File file2[] = file.listFiles();  
  344. //            } else {  
  345. //                deleteFile(pathname);  
  346. //  
  347. //            }  
  348. //            FtpClient.removeDirectory(pathname);  
  349. //        } catch (IOException ioe) {  
  350. //            ioe.printStackTrace();  
  351. //        }  
  352. //    }  
  353. //  
  354. //    /**  
  355. //     * 删除空目录  
  356. //     */  
  357. //    public static void deleteEmptyDirectory(String pathname) {  
  358. //        try {  
  359. //            connectServer();  
  360. //            FtpClient.removeDirectory(pathname);  
  361. //        } catch (IOException ioe) {  
  362. //            ioe.printStackTrace();  
  363. //        }  
  364. //    }  
  365.   
  366. //    /**  
  367. //     * 列出服务器上文件和目录  
  368. //     *  
  369. //     * @param regStr  
  370. //     *            --匹配的正则表达式  
  371. //     */  
  372. //    @SuppressWarnings("unchecked")  
  373. //    public static void listRemoteFiles(String regStr) {  
  374. //        connectServer();  
  375. //        try {  
  376. //            // FtpClient.changeWorkingDirectory(regStr);  
  377. //            String files[] = FtpClient.listNames(regStr);  
  378. //            if (files == null || files.length == 0)  
  379. //                System.out.println("There has not any file!");  
  380. //            else {  
  381. //                for (int i = 0; i < files.length; i ) {  
  382. //                    System.out.println(files[i]);  
  383. //  
  384. //                }  
  385. //  
  386. //            }  
  387. //        } catch (Exception e) {  
  388. //            e.printStackTrace();  
  389. //        }  
  390. //    }  
  391. //  
  392. //    /**  
  393. //     * 列出Ftp服务器上的所有文件和目录  
  394. //     *  
  395. //     */  
  396. //    public static void listRemoteAllFiles() {  
  397. //        connectServer();  
  398. //        try {  
  399. //            String[] names = FtpClient.listNames();  
  400. //            for (int i = 0; i < names.length; i ) {  
  401. //                System.out.println(names[i]);  
  402. //            }  
  403. //  
  404. //        } catch (Exception e) {  
  405. //            e.printStackTrace();  
  406. //        }  
  407. //    }  
  408.   
  409.     /** 
  410.      * 关闭连接 
  411.      */  
  412.     public static void closeConnect() {  
  413.         try {  
  414.             if (FtpClient != null) {  
  415.                 FtpClient.logout();  
  416.                 FtpClient.disconnect();  
  417.             }  
  418.         } catch (Exception e) {  
  419.             e.printStackTrace();  
  420.         }  
  421.     }  
  422.   
  423.     /** 
  424.      * 设置配置文件 
  425.      * 
  426.      * @param configFile 
  427.      */  
  428.     public static void setConfigFile(String configFile) {  
  429.         Ftp.ConfigFile = configFile;  
  430.     }  
  431.   
  432.     /** 
  433.      * 设置传输文件的类型[文本文件或者二进制文件] 
  434.      * 
  435.      * @param fileType--BINARY_FILE_TYPE、ASCII_FILE_TYPE 
  436.      */  
  437.     public static void setFileType(int fileType) {  
  438.         try {  
  439.             connectServer();  
  440.             FtpClient.setFileType(fileType);  
  441.         } catch (Exception e) {  
  442.             e.printStackTrace();  
  443.         }  
  444.     }  
  445.   
  446.     /** 
  447.      * 扩展使用 
  448.      * 
  449.      * @return 
  450.      */  
  451.     protected static FTPClient getFtpClient() {  
  452.         connectServer();  
  453.         return FtpClient;  
  454.     }  
  455.   
  456.     /** 
  457.      * 设置参数 
  458.      * 
  459.      * @param configFile 
  460.      *            --参数的配置文件 
  461.      */  
  462.     private static void setArg(String configFile) {  
  463.         Property = new Properties();  
  464.         BufferedInputStream inBuff = null;  
  465.         try {  
  466.             File file = new File(configFile);  
  467.   
  468.             inBuff = new BufferedInputStream(new FileInputStream(file));  
  469.   
  470.             Property.load(inBuff);  
  471.   
  472.             UserName = Property.getProperty("username");  
  473.             Password = Property.getProperty("password");  
  474.             Ip = Property.getProperty("ip");  
  475.             Port = Integer.parseInt(Property.getProperty("port"));  
  476.         } catch (FileNotFoundException e1) {  
  477.             System.out.println("配置文件 【" +configFile +"】不存在!");  
  478.             e1.printStackTrace();  
  479.         } catch (IOException e) {  
  480.             System.out.println("配置文件 【" +configFile+ "】无法读取!");  
  481.             e.printStackTrace();  
  482.         }  
  483.   
  484.         /* 
  485.          * } catch (Exception e) { e.printStackTrace(); } finally { try { if 
  486.          * (inBuff != null) inBuff.close(); } catch (Exception e) { 
  487.          * e.printStackTrace(); } } 
  488.          */  
  489.     }  
  490.   
  491.     /** 
  492.      * 连接到服务器 
  493.      * 
  494.      * @return true 连接服务器成功,false 连接服务器失败 
  495.      */  
  496.     public static boolean connectServer() {  
  497.         boolean flag = true;  
  498.         if (FtpClient == null) {  
  499.             int reply;  
  500.             try {  
  501.                 setArg(ConfigFile);  
  502.                 FtpClient = new FTPClient();  
  503.                 FtpClient.setControlEncoding("GBK");  
  504.                 FtpClient.setDefaultPort(Port);  
  505.                 FtpClient.configure(getFtpConfig());  
  506.                 FtpClient.connect(Ip);  
  507.                 FtpClient.login(UserName, Password);  
  508.                 FtpClient.setDefaultPort(Port);  
  509.                 //System.out.print(FtpClient.getReplyString());  
  510.                 reply = FtpClient.getReplyCode();  
  511.                 FtpClient.setDataTimeout(120000);  
  512.   
  513.                 if (!FTPReply.isPositiveCompletion(reply)) {  
  514.                     FtpClient.disconnect();  
  515.                     System.err.println("FTP server refused connection.");  
  516.                     // logger.debug("FTP 服务拒绝连接!");  
  517.                     flag = false;  
  518.                 }  
  519. //                System.out.println(i);  
  520. //                i ;  
  521.                  
  522.             } catch (SocketException e) {  
  523.                 flag = false;  
  524.                 e.printStackTrace();  
  525.                 System.err.println("登录ftp服务器【" +Ip+ "】失败,连接超时!");  
  526.                 // logger.debug("登录ftp服务器【" Ip "】失败");  
  527.             } catch (IOException e) {  
  528.                 flag = false;  
  529.   
  530.                 e.printStackTrace();  
  531.                 System.err.println("登录ftp服务器【"+ Ip +"】失败,FTP服务器无法打开!");  
  532.                 // logger.debug("登录ftp服务器【" Ip "】失败");  
  533.             }  
  534.   
  535.         }  
  536.         return flag;  
  537.     }  
  538.   
  539.     /** 
  540.      * 进入到服务器的某个目录下 
  541.      * 
  542.      * @param directory 
  543.      */  
  544.     public static void changeWorkingDirectory(String directory) {  
  545.         try {  
  546.             connectServer();  
  547.             FtpClient.changeWorkingDirectory(directory);  
  548.         } catch (IOException ioe) {  
  549.             ioe.printStackTrace();  
  550.         }  
  551.     }  
  552.   
  553. //    /**  
  554. //     * 返回到上一层目录  
  555. //     */  
  556. //    public static void changeToParentDirectory() {  
  557. //        try {  
  558. //            connectServer();  
  559. //            FtpClient.changeToParentDirectory();  
  560. //        } catch (IOException ioe) {  
  561. //            ioe.printStackTrace();  
  562. //        }  
  563. //    }  
  564.   
  565.     /** 
  566.      * 重命名文件 
  567.      * 
  568.      * @param oldFileName 
  569.      *            --原文件名 
  570.      * @param newFileName 
  571.      *            --新文件名 
  572.      */  
  573.     public static void renameFile(String oldFileName, String newFileName) {  
  574.         try {  
  575.             connectServer();  
  576.             FtpClient.rename(oldFileName, newFileName);  
  577.         } catch (IOException ioe) {  
  578.             ioe.printStackTrace();  
  579.         }  
  580.     }  
  581.   
  582.     /** 
  583.      * 设置FTP客服端的配置--一般可以不设置 
  584.      * 
  585.      * @return 
  586.      */  
  587.     private static FTPClientConfig getFtpConfig() {  
  588.         FTPClientConfig ftpConfig = new FTPClientConfig(  
  589.                 FTPClientConfig.SYST_UNIX);  
  590.         ftpConfig.setServerLanguageCode(FTP.DEFAULT_CONTROL_ENCODING);  
  591.         return ftpConfig;  
  592.     }  
  593.   
  594.     /** 
  595.      * 转码[ISO-8859-1 -> GBK] 不同的平台需要不同的转码 
  596.      * 
  597.      * @param obj 
  598.      * @return 
  599.      */  
  600.     private static String iso8859togbk(Object obj) {  
  601.         try {  
  602.             if (obj == null)  
  603.                 return "";  
  604.             else  
  605.                 return new String(obj.toString().getBytes("iso-8859-1"), "GBK");  
  606.         } catch (Exception e) {  
  607.             return "";  
  608.         }  
  609.     }  
  610.   
  611.     /** 
  612.      * 在服务器上创建一个文件夹 
  613.      * 
  614.      * @param dir 
  615.      *            文件夹名称,不能含有特殊字符,如 \ 、/ 、: 、* 、?、 "、 <、>... 
  616.      */  
  617.     public static boolean makeDirectory(String dir) {  
  618.         connectServer();  
  619.         boolean flag = true;  
  620.         try {  
  621.             // System.out.println("dir=======" dir);  
  622.             flag = FtpClient.makeDirectory(dir);  
  623.             if (flag) {  
  624.                 System.out.println("make Directory " +dir +" succeed");  
  625.   
  626.             } else {  
  627.   
  628.                 System.out.println("make Directory " +dir+ " false");  
  629.             }  
  630.         } catch (Exception e) {  
  631.             e.printStackTrace();  
  632.         }  
  633.         return flag;  
  634.     }  
  635.   
  636.     public static Log getLogger() {  
  637.         return logger;  
  638.     }  
  639.   
  640.     public static void setLogger(Log logger) {  
  641.         Ftp.logger = logger;  
  642.     }  
  643.   
原文地址:https://www.cnblogs.com/lzw0414/p/5411509.html