/**
* <p>Title:连接ftp服务器</p>
* <p>Description: 一个连接FTP的类,上传下载文件</p>
* @author yangtom
* @version 1.1
*/
public class FTP {
FtpClient client;
/**
* FTP服务器IP
*/
private String host="";
/**
* FTP用户名字
*/
private String username="";
/**
* FTP密码
*/
private String password="";
/**
* FTP端口
*/
private int port = 21;
public FTP(){
// Properties props = new Properties();
// try {
// props.load(getClass().getResourceAsStream(
// "/com/common/ApplicationResources.properties"));
// }
// catch (IOException ex) {
// ex.printStackTrace();
// }
ResourceBundle rb = ResourceBundle.getBundle(
"com.common.ApplicationResources");
host = rb.getString("ftp_host");
username = rb.getString("username");
password = rb.getString("password");
port = Integer.parseInt(rb.getString("port"));
}
/**
* 连接服务器方法
* @throws BaseException
*/
public void connect() throws BaseException{
try {
client = new FtpClient();
client.openServer(host,port);
client.login(username, password);
//设置成2进制传输
client.binary();
Logger.write("登陆成功:"+host);
}
catch (FtpLoginException e) {
Logger.write("无权限相连接" + e.getMessage());
throw new ApplicationException("error.sjdr.ftp.login");
}
catch(IOException e){
Logger.write("连接失败"+e.getMessage());
throw new ApplicationException("error.sjdr.ftp.connect");
}
catch(SecurityException e){
Logger.write("用户名字或者密码不对");
throw new ApplicationException("error.sjdr.ftp.security");
}
}
/**
* 上传文件
* @param hostFileName String 上传到ftp服务器的路径文件名
* @param localFilePath String 被上传文件在本地的路径文件名
* @return boolean 上传是否成功
*/
public boolean upLoad(String hostFileName,String localFilePath) {
try {
TelnetOutputStream os = client.put(hostFileName);
java.io.File file_in = new java.io.File(localFilePath);
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();
Logger.write("上传文件成功");
}
catch (Exception e) {
Logger.write("上传文件出错"+e.getMessage());
return false;
}
return true;
}
/**
* 下载文件
* @param hostFileName String 下载ftp服务器文件的路径文件名
* @param localFilePath String 下载到本地的路径文件名
* @return boolean
*/
public boolean download(String hostFileName,String localFilePath) {
File localFile = new File(localFilePath);
try {
TelnetInputStream is = client.get(hostFileName);
java.io.File file_in = new java.io.File(localFilePath);
FileOutputStream os = new FileOutputStream(file_in);
byte[] bytes = new byte[1024];
int c;
while ( (c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
}
is.close();
os.close();
Logger.write("下载文件成功");
}
catch (Exception e) {
Logger.write("下载文件出错"+e.getMessage());
return false;
}
return true;
}
/**
* 关闭ftp服务器
* @throws java.lang.Exception
*/
public void closeServer()throws Exception{
if(client!=null){
client.closeServer();
Logger.write("FTP已经关闭");
}
}