package ftp;
import sun.net.ftp.*;
import sun.net.*;
import java.io.*;
import java.io.IOException;
import sun.net.ftp.FtpClient;
public class test111 {
private FtpClient aftp;
private String msg;
private String hostname = "";
/**
* @param args
*/
public static void main(String[] args) {
String hostname = 服务器IP;
int port = 端口;
String uid = 用户名;
String pwd = 密码;
String RWFileDir = "D://temp//";//程序中文件的下载路径和保存路径是相同的
test111 ft = new test111();
ft.connect(RWFileDir, hostname, port, uid, pwd);
ft.downloadFile(RWFileDir, 文件名);
ft.stop();
}
public FtpClient connect(String RWFileDir, String hostname, int port,
String uid, String pwd) {
this.hostname = hostname;
System.out.println("Connecting to " + hostname + " , please wait......");
try {
this.aftp = new FtpClient(hostname, port);
this.aftp.login(uid, pwd);
this.aftp.binary();
// aftp.openPortDataConnection();
this.msg = "Connect to " + hostname + " success!";
System.out.println(this.msg);
} catch (FtpLoginException e) {
this.msg = "Login host " + hostname
+ " failed! Please check username and password : " + e;
System.out.println(this.msg);
} catch (IOException e) {
this.msg = "Connect to :" + hostname
+ " failed! Please check port : " + e;
System.out.println(this.msg);
} catch (SecurityException e) {
this.msg = "No competence connect to " + hostname
+ "! Please check competence; Error: " + e;
System.out.println(this.msg);
}
return this.aftp;
}
public void stop() {
String message = "";
try {
if (this.aftp != null) {
this.aftp.closeServer();
message = "disconnect to " + this.hostname + "!";
System.out.println(message);
}
} catch (IOException e) {
message = "connect to " + this.hostname + " failed!" + e;
System.out.println(message);
}
}
public boolean downloadFile(String RWFileDir, String filepathname) {
boolean result = true;
String message = "";
int ch;
if (this.aftp != null) {
System.out.println("Downloading file " + filepathname
+ ",please wait....");
try {
File fi = new File(RWFileDir + filepathname);
RandomAccessFile getFile = new RandomAccessFile(fi, "rw");
getFile.seek(0);
TelnetInputStream fget = this.aftp.get(filepathname);
DataInputStream puts = new DataInputStream(fget);
while ((ch = puts.read()) >= 0) {
getFile.write(ch);
}
fget.close();
getFile.close();
message = "Download " + filepathname + " file to " + RWFileDir
+ " directory success!";
System.out.println(message);
} catch (IOException e) {
message = "Download " + filepathname + " file to " + RWFileDir
+ " directory faild!" + e;
System.out.println(message);
result = false;
}
} else {
result = false;
}
return result;
}
}