FTP上傳下載

/**
 * ftp上傳下載工具類
 * <p>Title: FtpUtil</p>
 * <p>Description: </p>
 * <p>xxx</p> 
 * @author
 * @date
 * @version 
 */
public class FtpUtil {


/** 
* Description: 向FTP服務器上傳文件 
* @param host FTP服務器hostname 
* @param port FTP服務器端口 
* @param username FTP登錄賬號 
* @param password FTP登錄密碼 
* @param basePath FTP服務器基礎目錄
* @param filePath FTP服務器文件存放路徑。例如分日期存放:/2015/01/01。文件的路徑爲basePath+filePath
* @param filename 上傳到FTP服務器上的文件名 
* @param input 輸入流 
* @return 成功返回true,否則返回false 
*/  
public static boolean uploadFile(String host, int port, String username, String password, String basePath,
String filePath, String filename, InputStream input) {
boolean result = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(host, port);// 連接FTP服務器
// 如果採用默認端口,可以使用ftp.connect(host)的方式直接連接FTP服務器
ftp.login(username, password);// 登錄
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return result;
}
//切換到上傳目錄
if (!ftp.changeWorkingDirectory(basePath+filePath)) {
//如果目錄不存在創建目錄
String[] dirs = filePath.split("/");
String tempPath = basePath;
for (String dir : dirs) {
if (null == dir || "".equals(dir)) continue;
tempPath += "/" + dir;
if (!ftp.changeWorkingDirectory(tempPath)) {
if (!ftp.makeDirectory(tempPath)) {
return result;
} else {
ftp.changeWorkingDirectory(tempPath);
}
}
}
}
//設置上傳文件的類型爲二進制類型
ftp.setFileType(FTP.BINARY_FILE_TYPE);
//上傳文件
if (!ftp.storeFile(filename, input)) {
return result;
}
input.close();
ftp.logout();
result = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return result;
}

/** 
* Description: 從FTP服務器下載文件 
* @param host FTP服務器hostname 
* @param port FTP服務器端口 
* @param username FTP登錄賬號 
* @param password FTP登錄密碼 
* @param remotePath FTP服務器上的相對路徑 
* @param fileName 要下載的文件名 
* @param localPath 下載後保存到本地的路徑 
* @return 
*/  
public static boolean downloadFile(String host, int port, String username, String password, String remotePath,
String fileName, String localPath) {
boolean result = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(host, port);
// 如果採用默認端口,可以使用ftp.connect(host)的方式直接連接FTP服務器
ftp.login(username, password);// 登錄
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return result;
}
ftp.changeWorkingDirectory(remotePath);// 轉移到FTP服務器目錄
FTPFile[] fs = ftp.listFiles();
for (FTPFile ff : fs) {
if (ff.getName().equals(fileName)) {
File localFile = new File(localPath + "/" + ff.getName());


OutputStream is = new FileOutputStream(localFile);
ftp.retrieveFile(ff.getName(), is);
is.close();
}
}


ftp.logout();
result = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return result;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章