Java实现FTP上传下载功能

来源:互联网 发布:淘宝店铺授权书模板 编辑:程序博客网 时间:2024/04/27 09:28

package cn.voole.appplatform.util;
import java.io.DataInputStream; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.util.ArrayList; 
import java.util.List; 
import java.util.StringTokenizer;

import sun.net.TelnetInputStream; 
import sun.net.TelnetOutputStream; 
import sun.net.ftp.FtpClient; 
public class FtpUtil {
 
 private FtpClient ftpClient;
 /**
    * connectServer 连接ftp服务器
     * 
     * @throws java.io.IOException
     * @param path
     *            文件夹,空代表根目录
     * @param password
     *            密码
     * @param user
     *            登陆用户
     * @param server
     *            服务器地址
     */
 public void connectServer(String server, String user, String password, 
               String path) throws IOException { 
        ftpClient = new FtpClient(); 
        try{
         ftpClient.openServer(server);
        }catch(Exception e)
        {
         e.printStackTrace();
        }
        
        ftpClient.login(user, password); 
        // path是ftp服务下主目录的子目录  
        if (path.length() != 0) 
        {
         if(isDirExist(path)==false)
         {
          createDir(path);
         }
        }
            ftpClient.cd(path); 
        // 用2进制上传、下载  
        ftpClient.binary(); 
    }
 /**
  * @return 删除FTP服务器上指定的文件夹(包括删除文件夹中所有子文件)*
     */
 @SuppressWarnings("unchecked")
 public void deleteDirectory(String ftpDirectoryPath) throws IOException{
  List fileNames=this.getFileList(ftpDirectoryPath);
  for(Object fileName:fileNames)
  {
   ftpClient.sendServer("DELE " + fileName + "\r\n");
  }
  ftpClient.sendServer("XRMD " + ftpDirectoryPath + "\r\n");
 }
 /**
  * @return -1 文件不存在 -2 文件内容为空 >0 成功上传,返回文件的大小
  *@param newname
     *    上传后的新文件名
     * @param filename 
     *    上传的文件
     */
 public long upload(String filename, String newname) throws Exception { 
        long result = 0; 
        TelnetOutputStream os = null; 
        FileInputStream is = null; 
        try { 
            java.io.File file_in = new java.io.File(filename); 
            if (!file_in.exists()) 
                return -1; 
            if (file_in.length() == 0) 
                return -2; 
            os = ftpClient.put(newname); 
            result = file_in.length(); 
            is = new FileInputStream(file_in); 
            byte[] bytes = new byte[1024]; 
            int c; 
            while ((c = is.read(bytes)) != -1) { 
                os.write(bytes, 0, c); 
            } 
        } finally { 
            if (is != null) { 
                is.close(); 
            } 
            if (os != null) { 
                os.close(); 
            } 
        } 
        return result; 
    }
 
 public long upload(String filename) throws Exception { 
        String newname = ""; 
        if (filename.indexOf("/") > -1) { 
            newname = filename.substring(filename.lastIndexOf("/") + 1);
            filename = filename.substring(0,filename.lastIndexOf("/"));
        } else { 
            newname = filename; 
        } 
        return upload(filename, newname); 
    }
 /** @param newfilename
      *            本地生成的文件名
      * @param filename
      *            服务器上的文件名
      */
 public long download(String filename, String newfilename) throws Exception { 
        long result = 0; 
        TelnetInputStream is = null; 
        FileOutputStream os = null; 
        try { 
            is = ftpClient.get(filename); 
            java.io.File outfile = new java.io.File(newfilename); 
            os = new FileOutputStream(outfile); 
            byte[] bytes = new byte[1024]; 
            int c; 
            while ((c = is.read(bytes)) != -1) { 
                os.write(bytes, 0, c); 
                result = result + c; 
            } 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } finally { 
            if (is != null) { 
                is.close(); 
            } 
            if (os != null) { 
                os.close(); 
            } 
        } 
        return result; 
    }
 /**
     * 取得某个目录下的所有文件列表
     * 
     */ 
    @SuppressWarnings({ "unchecked", "deprecation" })
 public List getFileList(String path) { 
        List list = new ArrayList(); 
        try { 
            DataInputStream dis = new DataInputStream(ftpClient.nameList(path)); 
            String filename = ""; 
            while ((filename = dis.readLine()) != null) { 
                list.add(filename); 
            } 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
        return list; 
    }
    public void closeServer() throws IOException { 
        if (ftpClient != null) { 
            ftpClient.closeServer(); 
        } 
  } 
    /** 
     * 检查文件夹在当前目录下是否存在 
     *  
     * @param dir 
     * @return 
     */
    private boolean isDirExist(String dir) { 
        String pwd = ""; 
        try { 
            pwd = ftpClient.pwd(); 
            ftpClient.cd(dir); 
            ftpClient.cd(pwd); 
        } catch (Exception e) { 
            return false; 
        } 
        return true; 
    }
    /** 
     * 在当前目录下创建文件夹 
     *  
     * @param dir 
     * @return 
     * @throws Exception 
     */
    private boolean createDir(String dir) { 
        try { 
            ftpClient.ascii(); 
            StringTokenizer s = new StringTokenizer(dir, "/"); // sign 
            s.countTokens(); 
            String pathName = ftpClient.pwd(); 
            while (s.hasMoreElements()) { 
                pathName = pathName + "/" + (String) s.nextElement(); 
                try { 
                    ftpClient.sendServer("MKD " + pathName + "\r\n"); 
                } catch (Exception e) { 
                    e = null; 
                    return false; 
                } 
                ftpClient.readServerResponse(); 
            } 
            ftpClient.binary(); 
            return true; 
        } catch (IOException e1) { 
            e1.printStackTrace(); 
            return false; 
        } 
    }
}

ftp重启:/etc/rc.d/init.d/vsftpd start