ftp上傳與下載,這裏用到的是org.apache.commons.net.ftp.FTPClient工具類,.
上傳的思路:1.創建FTPClient對象,2.建立連接(對應的ip和port)3.登陸(username和password)4.得到返回值(ftp.getReplyCode())5.判斷這個返回值是不是有意義的(FTPReply.isPositiveCompletion(reply))如果沒有意義就是沒有完成的話,斷開ftp連接,返回false 6.如果應答碼有意義則更改路徑(ftp服務器的路徑),保存文件7.關閉輸入流,退出登錄,更改返回狀態爲true 8.斷開ftp連接
public static boolean uploadFile(String url,int port,String username,String password,String path,String fileName,InputStream in){
boolean success = false;
FTPClient ftp = new FTPClient();
try{
int reply;
ftp.connect(url,port);
ftp.login(username,password);
reply = ftp.getReplyCode();
if(!FTPReply.isPositiveCompletion(reply)){
ftp.disconnect();
return success;
}
ftp.changeWorkingDirectory(path);
ftp.storeFile(fileName,in);
in.close();
ftp.logout();
success=true;
}catch(IOException e){
e.printStackTrace();
}finally{
if(ftp.isConnected()){
ftp.disconnect();
}catch(IOException e){}
}
return success;
}
ftp下載1.創建FTPClient對象2.連接(url,port)3.登陸(username,password)4.獲得應答碼(ftp.getReplyCode)並判斷是不是有意義的應答碼(230),錯誤的(登陸信息不正確出現530錯誤碼;如果連接url不正確報連接超時;port不正確直接拋異常connection refused);5如果是沒有意義的(關閉連接,返回false)6如果應答有意義,更改連接路徑即遠程FTP服務器,ftp.listFiles();得到文件集合,並且遍歷和要下載的文件名相同的,生成輸出流,寫到要下載到的某地;
public static boolean download(String url,int port, String username,String password,String remotePath,String fileName,String localPath){
boolean success = false;
FTPClient ftp = new FTPClient();
try{
int reply;
ftp.connect(url,port);
ftp.login(username,password);
reply = ftp.getReplyCode();
if(!FTPReply.ispositiveCompletion(reply)){
ftp.disconnet();
return success;
}
ftp.changeWorkingDirectory(remotePath);
File[] files = ftp.listFiles();
for(File file : files){
if(file.getName().equals(filename)){
File f = new File(localPath+”/”+filename);
OutputStream output = new FileOutputStream(f);
ftp.retrieveFile(file.getName(), output);
output.close();
}
}
ftp.logout();
success = true;
}
return success;
}
參考:http://blog.csdn.net/hbcui1984/article/details/2720204