import java.io.FileInputStream;
import java.io.IOException;
import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;
import cn.com.ultrapower.ultraprocess.share.*;
public class FtpTool {
private FtpClient ftp;
private String romateDir="";
private String userName="";
private String password="";
private String host="";
private String port="21";
public FtpTool(String url)throws IOException
{
int len=url.indexOf("//");
String strTemp=url.substring(len+2);
len=strTemp.indexOf(":");
userName=strTemp.substring(0,len);
strTemp=strTemp.substring(len+1);
len=strTemp.indexOf("@");
password=strTemp.substring(0,len);
strTemp=strTemp.substring(len+1);
host="";
len=strTemp.indexOf(":");
if(len<0)//没有设置端口
{
len=strTemp.indexOf("/");
host=strTemp.substring(0,len);
strTemp=strTemp.substring(len+1);
}else
{
host=strTemp.substring(0,len);
strTemp=strTemp.substring(len+1);
len=strTemp.indexOf("/");
port=strTemp.substring(0,len);
strTemp=strTemp.substring(len+1);
}
romateDir=strTemp;
ftp = new FtpClient();
ftp.openServer(host, FormatInt.FormatStringToInt(port));
}
/**
* 构造方法,新建一个FtpClient对象,并打开FTP服务器
* @param host FTP服务器地址;port FTP服务端口
*
*/
public FtpTool(String host,int port)throws IOException{
ftp = new FtpClient();
ftp.openServer(host, port);
}
/**
* 登陆方法,通过用户名密码登陆到指定的FTP服务器上去,并返回欢迎信息
* @param username FTP用户名;password 密码
*
*/
public String login(String username,String password)throws IOException{
this.ftp.login(username, password);
if(!romateDir.equals(""))
ftp.cd(romateDir);
return this.ftp.welcomeMsg;
}
public String login()throws IOException{
this.ftp.login(userName, password);
if(!romateDir.equals(""))
ftp.cd(romateDir);
return this.ftp.welcomeMsg;
}
/**
* 此方法用来上传文件。
* @param pathname 本地路径;filename 要上传的文件名称
*/
public void upload(String pathname,String filename)throws IOException{
filename=FormatString.CheckNullString(filename);
if(filename.equals(""))
return;
if(!this.ftp.serverIsOpen()){
System.out.println("服务器连接不可用!");
}
this.ftp.binary();
TelnetOutputStream os = null;
FileInputStream is = null;
try {
//用ftp上传后的文件名与原文件名相同,同为filename变量内容
os = this.ftp.put(filename);
java.io.File file_in = new java.io.File(pathname+"//"+filename);
if (file_in.length()==0) {
System.out.println("上传文件为空!");
}
is = new FileInputStream(file_in);
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
}
} finally {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
}
System.out.println("上传文件成功!");
this.ftp.ascii();
}
public void download()
{
}
public void close()
{
try
{
if(ftp!=null)
ftp.closeServer();
}catch(Exception ex)
{
}
}