package com.sinosoft.sepmis.util; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; /** * Java自帶的API對FTP的操做 * @Title:Ftp.java * @author: shanhongzhi */ public class FtpUtil { /** * Description: 向FTP服務器上傳文件 * @param url FTP服務器hostname * @param port FTP服務器端口,若是默認端口請寫-1 * @param username FTP登陸帳號 * @param password FTP登陸密碼 * @param path FTP服務器保存目錄 * @param filename 上傳到FTP服務器上的文件名 * @param input 輸入流 * @return 成功返回true,不然返回false */ public static boolean uploadFile(String url, int port, String username, String password, String path, String filename, InputStream input) throws Exception { boolean success = false; FTPClient ftp = new FTPClient(); try { int reply; // 鏈接FTP服務器 if (port > -1) { ftp.connect(url, port); } else { ftp.connect(url); } // 登陸FTP ftp.login(username, password); reply = ftp.getReplyCode(); System.out.println(reply); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return success; } ftp.changeWorkingDirectory(path); ftp.storeFile(filename, input); input.close(); ftp.logout(); success = true; } catch (IOException e) { success = false; throw e; } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException e) { throw e; } } } return success; } public static void main(String agrs[]) { try { File file = new File("E:\\1.txt"); FileInputStream in = new FileInputStream(file); /* * 使用默認的端口號、用戶名、密碼以及根目錄鏈接FTP服務器 */ //返回true上傳成功,不然上傳失敗 // FtpUtil.uploadFile("192.168.61.209", -22, "instiaci", "instiaci", "/db2home/instiaci/personal/shanhz","2.txt",in); FtpUtil.uploadFile("192.168.61.104", 22, "administrator", "123456", "/sinopipi/IC","6.txt",in); } catch (Exception e) { e.printStackTrace(); } } }
說明:使用apache提供的commons-net-2.0.jar自帶的ftp功能,也能夠實現文件下載功能
java