java操作FTP,实现上传下载


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;
/*
 * @author   *
 */
class FTPUtil {
 /**
  * 连接到FTP
  * 
  * @param IP
  *            地址
  * @param userName
  *            用户名
  * @param passWord
  *            密码
  * @return FtpClient
  * @throws Exception
  */
 public FtpClient Connection(String IP, String userName, String passWord)
   throws Exception {
  FtpClient fc = new FtpClient();
  fc.openServer(IP);
  fc.login(userName, passWord);
  fc.binary();
  return fc;
 }
 /**
  * 断开连接
  * 
  * @param fc
  *            FTP连接对象
  * @throws IOException
  */
 public void Close(FtpClient fc) throws IOException {
  fc.closeServer();
 }
 /**
  * 获取当前工作作目录
  * 
  * @param fc
  *            FTP连接对象
  * @throws IOException
  */
 public String getPwd(FtpClient fc) throws IOException {
  return fc.pwd();
 }
 /**
  * 修改工作目录
  * 
  * @param fc
  * @param path
  *            子目录
  * @throws Exception
  */
 public void ftpCD(FtpClient fc, String path) throws Exception {
  fc.cd(path);
 }
 /**
  * 下载文件
  * 
  * @param fc
  *            FTP连接对象
  * @param filename
  *            下载的文件名称
  * @return InputStream
  * @throws Exception
  */
 public InputStream downLoad(FtpClient fc, String filename) throws Exception {
   fc.binary();
   return fc.get(filename);
 }
 /**
  * 上传文件
  * 
  * @param fc
  *            FTP连接对象
  * @param filename
  *            上传的文件名称
  * @throws Exception 
  */
 public void upLoad(FtpClient fc, String filename, String Url) throws Exception {
  
   TelnetOutputStream os = fc.put(filename);
   File file = new File(Url);
   FileInputStream is = new FileInputStream(file);
   byte[] bytes = new byte[1024];
   int c;
   while ((c = is.read(bytes)) != -1) {
    os.write(bytes, 0, c);
   }
    is.close();
    os.close();
 }
 /**
  * 删除指定文件
  * 
  * @param fc
  * @param filename
  * @throws Exception 
  */
 public void Delete(FtpClient fc, String filename) throws Exception {
   fc.cd(getPwd(fc));
   fc.readServerResponse();
 }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值