sun.net.ftp.FtpClient 实现简单上传下载
sun.net.ftp.FtpClient 可以帮助我们进行一些简单的ftp客户端功能:下载、上传文件,但如遇到创建目录之类的就无能为力了,我们只好利用第三方源码。1.文件的上传
System.out.println("开始建立连接");
FtpClient ftpClient=new FtpClient(ip,Integer.valueOf(sock).intValue());
ftpClient.login(username,pwd);
ftpClient.binary();
System.out.println("成功建立连接开始上传文件");
for(int i=0;i<filename.length;i++){
File f=new File(createfilepath+File.separator+filename);
System.out.println("开始上传文件:"+createfilepath+File.separator+filename);
if(!f.exists())continue;
FileInputStream fis=new FileInputStream(f);
TelnetOutputStream tos=ftpClient.put(uppath+File.separator+f.getName());
byte[] bt=new byte;
int len=0;
int lenTotal=0;
while((len=fis.read(bt))!=-1) {
lenTotal+=len;
tos.write(bt,0,len);
}
System.out.println("成功上传文件:"+createfilepath+File.separator+filename);
tos.close();
fis.close();
}
ftpClient.closeServer();
2.文件的下载
FtpClient ftpClient = new FtpClient(ip, Integer.valueOf(sock).intValue());
ftpClient.login(username, pwd);
BufferedReader reader = new BufferedReader(new InputStreamReader(ftpClient.nameList(downpath)));
ArrayList<String> nameList = new ArrayList<String>();
String s = "";
while( (s = reader.readLine()) != null){
if(s.indexOf(".xls")==-1 && s.indexOf(".dat")==-1)
nameList.add(s);
}
for(String filename : nameList){
File f = new File(filename);
if(!f.isDirectory()){
File fi = new File(downfilepath+File.separator+filename);
RandomAccessFile getFile = new RandomAccessFile(fi, "rw");
getFile.seek(0);
TelnetInputStream ins = ftpClient.get(downpath+File.separator+filename);
DataInputStream dins = new DataInputStream(ins);
String ss = "";
while((s = dins.readLine()) != null){
getFile.writeBytes(ss);
}
ins.close();
dins.close();
}
}
ftpClient.closeServer();
页:
[1]