package classTest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
public class FtpOperate {
private FTPClient client = new FTPClient();
/**
* 登入FTP,并傳回登入是否成功的Boolean值
* @param host
* @param port
* @param user
* @param password
* @return
*/
public boolean login(String host, int port, String user, String password) {
boolean flag = true;
try {
//防止亂碼,且設定編碼方式必須在連接配接ftp之前
client.setControlEncoding("GBK");
client.connect("192.168.19.190", 10086);
client.login("zqz", "123456");
} catch (Exception e) {
e.printStackTrace();
flag = false;
}
return flag;
}
/**
* 關閉FTP連接配接
*/
public void close() {
if(client.isConnected()) {
try {
client.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 在父級節點建立子節點目錄,如果父級節點為根節點parent可以為空或“/”
* @param parent
* @param path
* @return
*/
public boolean makeDir(String parent, String path) {
boolean flag = true;
flag = cdAssignPath(parent);
if(flag) {
try {
//建立已經存在的目錄會報錯
client.makeDirectory(path);
}catch (Exception e) {
e.printStackTrace();
flag = false;
}
}
return flag;
}
/**
* 上傳檔案
* @param path儲存FTP位置
* @param file要上傳的檔案
* @param remoteName在FTP儲存時的名字
*/
public void upload(String path, File file, String remoteName) {
try {
if(cdAssignPath(path)) {
System.out.println("==");
client.storeFile(remoteName, new FileInputStream(file));
}
}catch (Exception e) {
e.printStackTrace();
}
}
/**
* 下載下傳檔案
* @param remotePath
* @param remoteName
* @param localPath
* @param localName
*/
public void download(String remotePath, String remoteName, String localPath, String localName) {
if(cdAssignPath(remotePath)) {
try {
File file = new File(localPath);
if(!file.exists()) {
file.mkdirs();
}
FileOutputStream write = new FileOutputStream(new File(localPath + "/" + localName));
client.retrieveFile(remoteName, write);
write.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 擷取指定路徑下的檔案清單
* @param path
* @return
*/
public String[] ls(String path) {
if(cdAssignPath(path)) {
try {
return client.listNames();
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
/**
* 切換目前目錄到指定路徑,該路徑必須從根路徑("/")開始
* @param path
* @return
*/
public boolean cdAssignPath(String path) {
boolean flag = true;
try {
client.changeWorkingDirectory(path);
} catch (IOException e) {
e.printStackTrace();
flag = false;
}
return flag;
}
}