import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import sun.net.TelnetInputStream;
import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;
public class FtpTool {
String ip;
int port;
String user;
String pwd;
String remotePath;
String localPath;
FtpClient ftpClient;
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getRemotePath() {
return remotePath;
}
public void setRemotePath(String remotePath) {
this.remotePath = remotePath;
}
public String getLocalPath() {
return localPath;
}
public void setLocalPath(String localPath) {
this.localPath = localPath;
}
public FtpClient getFtpClient() {
return ftpClient;
}
public void setFtpClient(FtpClient ftpClient) {
this.ftpClient = ftpClient;
}
public boolean connectServer(String ip, int port, String user, String pwd)
throws Exception {
boolean isSuccess = false;
try {
ftpClient = new FtpClient();
ftpClient.openServer(ip, port);
ftpClient.login(user, pwd);
isSuccess = true;
} catch (Exception ex) {
throw new Exception("Connect ftp server error:" + ex.getMessage());
}
return isSuccess;
}
public void downloadFile(String remotePath,String localPath, String filename) throws Exception {
try {
if (connectServer(getIp(), getPort(), getUser(), getPwd())) {
if (remotePath.length() != 0)
ftpClient.cd(remotePath);
ftpClient.binary();
TelnetInputStream is = ftpClient.get(filename);
File file_out = new File(localPath + File.separator + filename);
FileOutputStream os = new FileOutputStream(file_out);
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
}
is.close();
os.close();
ftpClient.closeServer();
}
} catch (Exception ex) {
throw new Exception("ftp download file error:" + ex.getMessage());
}
}
public void uploadFile(String remotePath,String localPath, String filename) throws Exception {
try {
if (connectServer(getIp(), getPort(), getUser(), getPwd())) {
if (remotePath.length() != 0)
ftpClient.cd(remotePath);
ftpClient.binary();
TelnetOutputStream os = ftpClient.put(filename);
File file_in = new File(localPath + File.separator + filename);
FileInputStream is = new FileInputStream(file_in);
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
}
is.close();
os.close();
ftpClient.closeServer();
}
} catch (Exception ex) {
throw new Exception("ftp upload file error:" + ex.getMessage());
}
}
}
|