Home > Java > javaTutorial > body text

How to implement ftp upload and download, delete files and upload folders on ftp server in Java

高洛峰
Release: 2017-01-11 15:05:51
Original
1725 people have browsed it

A JAVA code that implements the FTP function, including the server setting module, and includes common methods for uploading files to FTP, downloading files, deleting files, uploading folders on the ftp server, and detecting whether the folder exists. Wait, some of the codes in it may be of reference value for writing JAVA file uploads. Java FTP main file code:

package ftpDemo;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import sun.net.TelnetInputStream;
import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;
public class ftpUtil {
// 上传文件至FTP通用方法
public static void upLoadFileFtp(KmConfig kmConfig,InputStream is, String fileName){
  try {
    String ftpHost = kmConfig.getFtpHost();
    int port = kmConfig.getFtpPort();
    String userName = kmConfig.getFtpUser();
    String passWord = kmConfig.getFtpPassword();
    String path = kmConfig.getFtpPath();
    FtpClient ftpClient = new FtpClient(ftpHost, port);// ftpHost为FTP服务器的IP地址,port为FTP服务器的登陆端口,ftpHost为String型,port为int型。
    ftpClient.login(userName, passWord);// userName、passWord分别为FTP服务器的登陆用户名和密码
    ftpClient.binary();
    ftpClient.cd(path);// path为FTP服务器上保存上传文件的路径。
    TelnetOutputStream telnetOut = ftpClient.put(fileName);// fileName为上传的文件名
    DataOutputStream dataOut = new DataOutputStream(telnetOut);
    byte buffer[] = new byte[ * ];
    int count = ;
    while ((count = is.read(buffer)) != -) {
      dataOut.write(buffer, , count);
    }
    telnetOut.close();
    dataOut.close();
    ftpClient.closeServer();
  } catch (Exception e) {
    System.out.println("上传文件失败!请检查系统FTP设置,并确认FTP服务启动");
  }
}
// 删除文件至FTP通用方法
public static void deleteFileFtp(KmConfig kmConfig,String fileName){
  try {
    String ftpHost = kmConfig.getFtpHost();
    int port = kmConfig.getFtpPort();
    String userName = kmConfig.getFtpUser();
    String passWord = kmConfig.getFtpPassword();
    String path = kmConfig.getFtpPath();
    FtpClient ftpClient = new FtpClient(ftpHost, port);// ftpHost为FTP服务器的IP地址,port为FTP服务器的登陆端口,ftpHost为String型,port为int型。
    ftpClient.login(userName, passWord);// userName、passWord分别为FTP服务器的登陆用户名和密码
    ftpClient.binary();
    ftpClient.cd(path);// path为FTP服务器上保存上传文件的路径。
    try {
      ftpClient.sendServer("dele " + fileName + "\r\n");
    } catch (Exception e) {
      System.out.println("删除文件失败!请检查系统FTP设置,并确认FTP服务启动");
    }
    ftpClient.closeServer();
  } catch (Exception e) {
    System.out.println("删除文件失败!");
  }
}
// 下载ftp文件
public static void downloadFileFtp(KmConfig kmConfig,String fileName, String clientFileName, OutputStream outputStream){
  try {
    String ftpHost = kmConfig.getFtpHost();
    int port = kmConfig.getFtpPort();
    String userName = kmConfig.getFtpUser();
    String passWord = kmConfig.getFtpPassword();
    String path = kmConfig.getFtpPath();
    FtpClient ftpClient = new FtpClient(ftpHost, port);// ftpHost为FTP服务器的IP地址,port为FTP服务器的登陆端口,ftpHost为String型,port为int型。
    ftpClient.login(userName, passWord);// userName、passWord分别为FTP服务器的登陆用户名和密码
    ftpClient.binary();
    ftpClient.cd(path);// path为FTP服务器上保存上传文件的路径。
    try {
      TelnetInputStream in = ftpClient.get(fileName);
      byte[] bytes = new byte[];
      int cnt=;
      while ((cnt=in.read(bytes,,bytes.length)) != -) {
        outputStream.write(bytes, , cnt);
      }
      outputStream.close();
      in.close();
    } catch (Exception e) {
      ftpClient.closeServer();
      e.printStackTrace();
    }
    ftpClient.closeServer();
  } catch (Exception e) {
    System.out.println("下载文件失败!请检查系统FTP设置,并确认FTP服务启动");
  }
}
//在ftp服务器上传件文件夹
  public boolean createDir(String path,FtpClient ftpClient) throws Exception{
      //进入到home文件夹下
      ftpClient.cd("/home");
      //创建远程文件夹
      //远程命令包括
      //USER  PORT  RETR  ALLO  DELE  SITE  XMKD  CDUP  FEAT<br>
//     PASS  PASV  STOR  REST  CWD   STAT  RMD   XCUP  OPTS<br>
//     ACCT  TYPE  APPE  RNFR  XCWD  HELP  XRMD  STOU  AUTH<br>
//     REIN  STRU  SMNT  RNTO  LIST  NOOP  PWD   SIZE  PBSZ<br>
//     QUIT  MODE  SYST  ABOR  NLST  MKD   XPWD  MDTM  PROT<br>
//        在服务器上执行命令,如果用sendServer来执行远程命令(不能执行本地FTP命令)的话,所有FTP命令都要加上/r/n<br>
//          ftpclient.sendServer("XMKD /test/bb/r/n"); //执行服务器上的FTP命令<br>
//          ftpclient.readServerResponse一定要在sendServer后调用<br>
//          nameList("/test")获取指目录下的文件列表<br>
//          XMKD建立目录,当目录存在的情况下再次创建目录时报错<br>
//          XRMD删除目录<br>
//          DELE删除文件<br>
    //通过远程命令 穿件一个files文件夹
    ftpClient.sendServer("MKD "+ path + "\r\n");
    //这个方法必须在 这两个方法中间调用 否则 命令不管用
    ftpClient.binary();
    ftpClient.readServerResponse();
    return false;
  }
/**
 * 检查文件夹是否存在
 * @param dir
 * @param ftpClient
 * @return
 */
  public boolean isDirExist(String dir, FtpClient ftpClient) {
     try {
      ftpClient.cd(dir);
    } catch (Exception e) {
      return false;
    }
    return true;
  }
}
Copy after login

KmConfig.java code is as follows: Define FTP server parameters, including login user name and password.

package ftpDemo;
public class KmConfig {
  //主机ip
  private String FtpHost = "";
  //端口号
  private int FtpPort;
  //ftp用户名
  private String FtpUser = "";
  //ftp密码
  private String FtpPassword = "";
  //ftp中的目录
  private String FtpPath = "";
  public String getFtpHost() {
    return FtpHost;
  }
  public void setFtpHost(String ftpHost) {
    FtpHost = ftpHost;
  }
  public int getFtpPort() {
    return FtpPort;
  }
  public void setFtpPort(int ftpPort) {
    FtpPort = ftpPort;
  }
  public String getFtpUser() {
    return FtpUser;
  }
  public void setFtpUser(String ftpUser) {
    FtpUser = ftpUser;
  }
  public String getFtpPassword() {
    return FtpPassword;
  }
  public void setFtpPassword(String ftpPassword) {
    FtpPassword = ftpPassword;
  }
  public String getFtpPath() {
    return FtpPath;
  }
  public void setFtpPath(String ftpPath) {
    FtpPath = ftpPath;
  }
}
Copy after login

The following is the test code:

package ftpDemo;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class Test {
  public static void main(String[] args) {
    //设置ftp
    KmConfig km = new KmConfig();
    km.setFtpHost("...");
    km.setFtpPort();
    km.setFtpUser("test");
    km.setFtpPassword("");
    km.setFtpPath("KM");
    //上传到ftp
    ftpUtil util=new ftpUtil();
    File file = new File("F:/文章.jpg");
    InputStream in;
    try {
      in = new FileInputStream(file);
      util.upLoadFileFtp(km, in, "更改后的名字.jpg");
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}
Copy after login

The above code is the editor's introduction to how to implement ftp upload and download, delete files and upload folders on the ftp server in Java. I hope you like it.

For more Java methods to implement ftp upload and download, delete files and upload folders on the ftp server, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template