import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import sun.net.TelnetInputStream;
import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;
public class ftp
{
private FtpClient ftpClient ;
private String FtpServer = "192.168.0.8";
private String FtpPort = "21";
private String FtpUser = "root";
private String FtpPwd = "root";
public ftp()
{
}
public ftp(String pm_sFtpServer,String pm_sFtpPort,String pm_sFtpUser,String pm_sFtpPwd)
{
this.FtpServer = pm_sFtpServer;
this.FtpPort = pm_sFtpPort;
this.FtpUser = pm_sFtpUser;
this.FtpPwd = pm_sFtpPwd;
}
/*
* 连接FTP服务器
*/
public void login()
{
try
{
this.ftpClient = new FtpClient(this.FtpServer,Integer.parseInt(this.FtpPort));
//登陆服务端FTP,设定ascii传输方式
this.ftpClient.openServer(this.FtpServer);
this.ftpClient.login(this.FtpUser,this.FtpPwd);
this.ftpClient.ascii();
}
catch (NumberFormatException e)
{
System.out.println("FTPTools:FTP连接错误!");
e.printStackTrace();
}
catch (IOException e)
{
System.out.println("FTPTools:FTP连接错误!");
e.printStackTrace();
}
}
public void stop()
{
String message = "";
try
{
if(ftpClient!=null)
{
ftpClient.closeServer();
message = "与主机"+FtpServer+"连接已断开!";
System.out.println(message);
}
}
catch(IOException e)
{
message = "与主机"+FtpServer+"断开连接失败!"+e;
System.out.println(message);
}
}
/*
* @完成文件下载操作
* @param pm_sServerFilePath 服务器文件路径
* @param pm_sServerFileName 服务器文件名
* @param pm_sDesPath 客户端下载文件存放路径
*/
public void download(String pm_sServerFilePath,String pm_sServerFileName,String pm_sDesPath)
{
try
{
login();
//进入下载目录
this.ftpClient.cd(pm_sServerFilePath);
//流转换,完成下载操作
TelnetInputStream ins = this.ftpClient.get(pm_sServerFileName);
FileOutputStream ous = new FileOutputStream(pm_sDesPath+"//"+pm_sServerFileName);
byte[] tmp = new byte[1024];
int lenth = 0;
while((lenth = ins.read(tmp))!=-1)
{
ous.write(tmp,0,lenth);
}
//ous.flush();
ins.close();
ous.close();
}
catch (IOException e)
{
System.out.println("FTP下载错误!");
e.printStackTrace();
}
}
/*
* @完成文件传送操作
* @param pm_oSrcFile
*/
public void upload(File pm_oSrcFile,String pm_sServerFilePath)
{
try
{
login();
//进入上传目录
this.ftpClient.cd(pm_sServerFilePath);
//流转换,完成上传操作
TelnetOutputStream out = this.ftpClient.put(pm_oSrcFile.getName());
FileInputStream ins = new FileInputStream(pm_oSrcFile);
byte[] tmp = new byte[1024];
int lenth = 0;
while((lenth = ins.read(tmp))!=-1)
{
out.write(tmp,0,lenth);
}
//out.flush();
out.close();
ins.close();
}
catch (IOException e)
{
System.out.println("FTP上传错误!");
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception
{
//ftp f = new ftp("192.168.0.29","21","temp","temp");
ftp f = new ftp();
f.download("/opt/sfcl/oaj/data","2006-08-31-08","temp");
//File uploadfile = new File("list.java");
//f.upload(uploadfile,"data");
f.stop();
Thread.sleep(10000);
}
}