| 本文介绍如何通过java代码访问ftp服务器,从而实现ftp客户端 请看如下代码
package ftp;
import sun.net.ftp.FtpClient;
import java.io.*;
import sun.net.*;
import java.util.*;
public class Ftp {
private TelnetInputStream fget;
private DataInputStream puts;
private final int BUFFER=2048;
private static String ftpServer;
private static String user;
private static String pass;
final private static String CONFIGFILE = "config.txt";
public Ftp() {
try {
if(ftpServer==null){
Properties p = new Properties();
FileInputStream fin=new FileInputStream(CONFIGFILE);
p.load(fin);
ftpServer=p.getProperty("server");
user=p.getProperty("user");
pass=p.getProperty("pass");
fin.close();
}
}
catch (IOException ex) {
ex.printStackTrace();
}
}
public FtpClient getFtp(){
FtpClient fc;
try{
fc = new FtpClient(ftpServer);
if(!(user==null||user.equals(""))){
fc.login(user, pass);
}
fc.binary();
return fc;
}catch(Exception e){
e.printStackTrace();
return null;
}
}
public void cd(FtpClient fc,String dir){
try {
fc.cd(dir);
}
catch (IOException ex) {
ex.printStackTrace();
}
}
public boolean downFile(FtpClient fc,String ftpDir,String ftpFileName,String localDir,String localFileName){
try{
int off=0;
int len;
byte data[]=new byte[BUFFER];
FileOutputStream getFile;
getFile = new FileOutputStream(localDir + localFileName,false);
fc.cd(ftpDir);
fget=fc.get(ftpFileName);
puts = new DataInputStream(fget);
while ((len=puts.read(data))>= 0){
getFile.write(data,0,len);
getFile.flush();
}
getFile.close();
return true;
}
catch (Exception ex){
ex.printStackTrace();
return false;
}
}
public static void main(String[] args) throws Exception{
Ftp ftpClient1 = new Ftp();
FtpClient f =ftpClient1.getFtp();
//f.login("","");
System.out.println(f.welcomeMsg);
TelnetInputStream tis =f.list();
OutputStream os = new FileOutputStream("c:\\te.t");
byte[] b =new byte[tis.available()];
tis.read(b);
tis.close();
os.write(b);
os.flush();
os.close();
}
}
|