Java实现ftp操作~


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

public class FtpUtil {

public static FTPClient openFTP(String url, String username, String password) throws IOException
{
FTPClient ftp = new FTPClient();
ftp.setControlEncoding("gb2312");
ftp.connect(url);//连接FTP服务器 ,默认端口
//如采用端口,用ftp.connect(url,port)的方式直接连接FTP服务器
ftp.login(username, password);//登录
System.out.println("连接成功!");
return ftp;
}

public static void closeFTP(FTPClient ftp) throws IOException
{
ftp.disconnect();
System.out.println("关闭FTP!");
return ;
}

public static void newDir(FTPClient ftp, String path, String dir) throws IOException
{
ftp.changeWorkingDirectory(path);
ftp.makeDirectory(dir);
System.out.println("创建文件夹成功!");
return ;
}

public static void fileList(FTPClient ftp,String path) throws IOException
{
ftp.changeWorkingDirectory(path);
FTPFile[] file=ftp.listFiles(path);
for(int i=0;i<file.length;i++)
{
String tmp=file[i].getName();
if(file[i].getType()==1)
{
System.out.println("文件夹:"+tmp);
fileList(ftp, (path+ tmp+"/"));
}
else
{
System.out.println(file[i].getName()+"\t"+file[i].getType()+"\t"+file[i].getSize());
}
}
return ;
}

public static void uploadFile(FTPClient ftp,String path,String filename, FileInputStream input) throws IOException
{
ftp.changeWorkingDirectory(path);
ftp.storeFile(filename, input);
input.close();
return ;
}

public static void downloadFile(FTPClient ftp, String remotePath, String fileName, String localPath) throws IOException
{
ftp.changeWorkingDirectory(remotePath);//转移到FTP服务器目录
FTPFile[] fs = ftp.listFiles();
for (FTPFile ff : fs)
{
if (ff.getName().equals(fileName))
{
File localFile = new File(localPath + "/" + ff.getName());
OutputStream is = new FileOutputStream(localFile);
ftp.retrieveFile(ff.getName(), is);
is.close();
}
}
return ;
}


public static void main(String[] args) throws IOException
{
FTPClient ftp=openFTP("IP","name", "passwd"); //连接ftp
ftp.enterLocalPassiveMode(); // Use passive mode as default because most of us are behind firewalls these days.
ftp.setFileType(FTP.BINARY_FILE_TYPE); // 二进制文件支持!!!
newDir(ftp, "/test", "newDir"); // 在/test目录下创建文件夹
fileList(ftp, "/"); //列出目录下所有的文件
String fileName = "test.docx";
File uploadFile = new File("C:" + File.separator + fileName);
uploadFile(ftp, "/test/", "test.docx", new FileInputStream(uploadFile));
downloadFile(ftp, "/test", "test.docx", "D:\\");
closeFTP(ftp);

}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值