ftplist部分是用来显示ftp服务器上的文件;
getbutton部分为从ftp服务器下传一个文件;
putbutton部分为向ftp服务器上传一个文件。
别忘了在程序中还要引入两个库文件(import sun.net.*,import sun.net.ftp.*)。
以下是这三部分的java源程序:
(1)显示ftp服务器上的文件
void ftplist_actionperformed(actionevent e) {
string server=serveredit.gettext();
//输入的ftp服务器的ip地址
string user=useredit.gettext();
//登录ftp服务器的用户名
string password=passwordedit.gettext();
//登录ftp服务器的用户名的口令
string path=pathedit.gettext();
//ftp服务器上的路径
try {
ftpclient ftpclient=new ftpclient();
//创建ftpclient对象
ftpclient.openserver(server);
//连接ftp服务器
ftpclient.login(user, password);
//登录ftp服务器
if (path.length()!=0) ftpclient.cd(path); telnetinputstream is=ftpclient.list(); int c; while ((c=is.read())!=-1) { system.out.print((char) c);} is.close(); ftpclient.closeserver();//退出ftp服务器 } catch (ioexception ex) {;} } |
(2)从ftp服务器上下传一个文件
void getbutton_actionperformed(actionevent e) { string server=serveredit.gettext(); string user=useredit.gettext(); string password=passwordedit.gettext(); string path=pathedit.gettext(); string filename=filenameedit.gettext(); try { ftpclient ftpclient=new ftpclient(); ftpclient.openserver(server); ftpclient.login(user, password); if (path.length()!=0) ftpclient.cd(path); ftpclient.binary(); telnetinputstream is=ftpclient.get(filename); file file_out=new file(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 (ioexception ex) {;} } |
(3)向ftp服务器上上传一个文件
void putbutton_actionperformed(actionevent e) { string server=serveredit.gettext(); string user=useredit.gettext(); string password=passwordedit.gettext(); string path=pathedit.gettext(); string filename=filenameedit.gettext(); try { ftpclient ftpclient=new ftpclient(); ftpclient.openserver(server); ftpclient.login(user, password); if (path.length()!=0) ftpclient.cd(path); ftpclient.binary(); telnetoutputstream os=ftpclient.put(filename); file file_in=new file(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 (ioexception ex) {;} } } |