ftp实现上传
采用 apache的 commons-net包java 代码
[*]import java.io.FileInputStream;
[*]import java.io.IOException;
[*]
[*]import org.apache.commons.net.ftp.FTP;
[*]import org.apache.commons.net.ftp.FTPClient;
[*]import org.apache.commons.net.ftp.FTPReply;
[*]import org.apache.log4j.Logger;
[*]
[*]public class FtpUtil {
[*] private Logger log = Logger.getLogger(this.getClass());
[*] private String ftpServer;
[*] private String userName;
[*] private String pswd;
[*]
[*] public void setFtpServer(String ftpServer) {
[*] this.ftpServer = ftpServer;
[*] }
[*]
[*] public void setPswd(String pswd) {
[*] this.pswd = pswd;
[*] }
[*]
[*] public void setUserName(String userName) {
[*] this.userName = userName;
[*] }
[*]
[*] /**
[*] * 连接Ftp服务器
[*] * @return
[*] * @throws SmpBizException
[*] */
[*] public FTPClient loginToFtpServer() throws Exception {
[*]
[*] FTPClient ftp = new FTPClient();
[*] try {
[*] ftp.connect(this.ftpServer);
[*] int reply = ftp.getReplyCode();
[*] if(!FTPReply.isPositiveCompletion(reply)){
[*] log.error("Ftp connect to "+this.ftpServer +" failed!");
[*] throw new Exception("Ftplogin to connect to "+this.ftpServer +" failed!");
[*] }
[*] ftp.login(this.userName,this.pswd);
[*] log.debug("Ftp connect to "+this.ftpServer +" success!");
[*]
[*] } catch (Exception e) {
[*] log.error("Ftp connect "+this.ftpServer +" failed!!");
[*] throw new Exception("FtpLogin to "+this.ftpServer +" failed!!");
[*] }
[*] return ftp;
[*] }
[*]
[*] /**
[*] * Ftp文件到服务器
[*] * @param remotPath
[*] * @param localFile
[*] * @param remoteFileName
[*] * @throws SmpBizException
[*] */
[*] public void upload(String remotPath,String localFile,String remoteFileName) throws Exception{
[*] FTPClient ftp = this.loginToFtpServer();
[*] FileInputStream in = null;
[*] try {
[*] log.debug("--- ftp begin! ---");
[*] ftp.setFileType(FTP.BINARY_FILE_TYPE);
[*] ftp.enterLocalPassiveMode();
[*] if(null!=remotPath&&(!ftp.changeWorkingDirectory(remotPath))){
[*] ftp.makeDirectory( remotPath );
[*] ftp.changeWorkingDirectory( remotPath );
[*] }
[*]
[*] in = new FileInputStream(localFile);
[*] ftp.storeFile(remoteFileName, in);
[*] log.debug("--- ftp finish! ---");
[*] } catch (IOException e) {
[*] log.error("ftp file:"+ localFile +" fail!!!");
[*] throw new Exception("ftp file:"+ localFile +" fail!!!");
[*] }finally{
[*] try {
[*] ftp.disconnect();
[*] if(null!=in){
[*] in.close();
[*] }
[*] } catch (IOException e) {
[*] this.log.error("close connect failed!");
[*] e.printStackTrace();
[*] }
[*] }
[*] }
[*]
[*] /**
[*] * 远程文件路径编码(上传到ftp上的文件路径)
[*] *
[*] * @param remoteFilePath
[*] * @return
[*] */
[*] protected String enCodingRemoteFilePath(String remoteFilePath) {
[*] return null;
[*] }
[*]
[*]}
页:
[1]