JDK1.7 Above javaFTP upload and delete file implementation method

  • 2020-11-25 07:16:15
  • OfStack

Examples are as follows:


packagecom.itv.launcher.util;
 
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.IOException;
importjava.net.InetSocketAddress;
importjava.util.Properties;
importjava.util.StringTokenizer;
 
importsun.net.TelnetOutputStream;
importsun.net.ftp.FtpClient;
importsun.net.ftp.FtpProtocolException;
 
/**
 *
 FTP Upload tool class 
 *
 *
 @author yanzhou
 *
 @version v1.0
 */
publicclass
FTPUtil {
 
  privatestatic
FtpClient ftpClient = null;
  privatestatic
final 
String url;
  privatestatic
final 
int 
port;
  privatestatic
final 
String user;
  privatestatic
final 
String password;
  privatestatic
final 
String remoteFilePath;
 
  static{
    Properties
 FTPPro = ReadFTPProperties.getMsgFromPro();
    url
 = FTPPro.getProperty("FTP_URL");
    port
 = Integer.parseInt(FTPPro.getProperty("FTP_PORT"));
    user
 = FTPPro.getProperty("FTP_USER");
    password
 = FTPPro.getProperty("FTP_PASSWORD");
    remoteFilePath
 = FTPPro.getProperty("FTP_REMOTE_FILEPATH");
 
  }
 
  /**
   *
  link FTP
   *
 @throws FtpProtocolException 
   */
  privatestatic
void 
connectFTP() throwsFtpProtocolException
 {
    try{
      ftpClient
 = FtpClient.create();
      ftpClient.connect(newInetSocketAddress(url,
 port));
      ftpClient.login(user,
 password.toCharArray());
      ftpClient.setBinaryType();
      if(!"".equals(remoteFilePath)
 && remoteFilePath != null)
 {
        ftpClient.changeDirectory(remoteFilePath);
      }
    }catch(IOException
 e) {
      e.printStackTrace();
    }
  }
 
  /**
   *
  Shut down FTP link 
   */
  publicstatic
void 
closeFTP() {
    try{
      if(ftpClient
 != null)
 {
        ftpClient.close();
      }
    }catch(IOException
 e) {
      e.printStackTrace();
    }
  }
 
  /**
   *
  Upload file to FTP
   *
 @param file file File, struts2 From the page File type 
   *
 @param filePath  To keep in FTP Path (folder) on 
   *
 @param fileName  The file name ( test001.jpg ) 
   *
 @return  Whether the file was uploaded successfully 
   *
 @throws Exception
   */
  publicstatic
boolean 
upload(File file, String filePath, String fileName) {
    TelnetOutputStream
 to = null;
    FileInputStream
 fi = null;
    filePath
 = remoteFilePath + Constants.FILE_SEPARATOR + filePath;
    try{
      if(file
 != null)
 {
        connectFTP();
        if(!isDirExist(filePath.replace("\\","/")))
 {
          createDir(filePath.replace("\\","/"));
          ftpClient.changeDirectory(filePath.replace("\\","/"));
        }
        fi
 = newFileInputStream(file);
        to
 = (TelnetOutputStream) ftpClient.putFileStream(fileName, true);
        byte[]
 bytes = newbyte[1024];
        inti
 = fi.read(bytes);
        while(i
 != -1)
 {
          to.write(bytes);
          i
 = fi.read(bytes);
        }
      }
      returntrue;
    }catch(FileNotFoundException
 e1) {
      returnfalse;
    }catch(IOException
 e2) {
      returnfalse;
    }catch(Exception
 e) {
      returnfalse;
    }finally{
      if(fi
 != null)
 {
        try{
          fi.close();
        }catch(IOException
 e) {
          e.printStackTrace();
        }
      }
      if(to
 != null)
 {
        try{
          to.flush();
          to.close();
        }catch(IOException
 e) {
          e.printStackTrace();
        }
      }
      closeFTP();
    }
  }
 
  /**
   *
  delete FTP Specify the files in the directory 
   *
 @param filePath  The file in FTP Path to storage 
   *
 @param fileName  The name of the file to delete 
   *
 @return  Whether the deletion is successful 
   */
  publicstatic
boolean 
deleteFileFtp(String filePath, String fileName){ 
    try{
      connectFTP();
      filePath
 = remoteFilePath + Constants.FILE_SEPARATOR + filePath + Constants.FILE_SEPARATOR;
      if(!isDirExist(filePath.replace("\\","/")))
 {
        returnfalse;
      }
      ftpClient.changeDirectory(filePath.replace("\\","/"));
      ftpClient.deleteFile(fileName);
      returntrue;
    }catch(Exception
 e) {
      e.printStackTrace();
      returnfalse;
    }finally{
      closeFTP();
    }
  }
  /**
   *
  Check if the folder exists 
   *
   *
 @param dir
   *
 @param ftpClient
   *
 @return
   */
  privatestatic
Boolean isDirExist(String dir) {
    try{
      ftpClient.changeDirectory(dir);
    }catch(Exception
 e) {
      returnfalse;
    }
    returntrue;
  }
 
  /**
   *
  Create folder 
   *
   *
 @param dir
   *
 @param ftpClient
   *
 @throws Exception
   */
  privatestatic
void 
createDir(String dir) throwsException
 {
    ftpClient.setAsciiType();
    StringTokenizer
 s = newStringTokenizer(dir,
"/");//
 sign
    s.countTokens();
    String
 pathName = "";
    while(s.hasMoreElements())
 {
      pathName
 = pathName + "/"+
 (String) s.nextElement();
      try{
        ftpClient.makeDirectory(pathName);
      }catch(Exception
 e) {
        e
 = null;
      }
    }
    ftpClient.setBinaryType();
 
  }
 
}

2. Constant class, system path separator


packagecom.itv.launcher.util;
 
publicinterface
Constants {
   
  // Path separator 
  publicstatic
String FILE_SEPARATOR = System.getProperty("file.separator");
}

3. FTP link configuration properties file, including username and password 1 some information


#FTP the IP address 
FTP_URL=127.0.0.1
#FTP The port number 
FTP_PORT=1234
# The user name 
FTP_USER=yanzhou
# password 
FTP_PASSWORD=abcdefg12345
#FTP Account directory 
FTP_REMOTE_FILEPATH=

Related articles: