JAVA中使用FTPClient工具类上传下载

在JAVA程序中,经常需要和FTP打交道,比如向FTP服务器上传文件、下载文件。本文简单介绍如何利用jakarta commons中的FTPClient(在commons-net包中)实现上传下载文件。

1、写一个javabean文件,描述ftp上传或下载的信息

public class FtpUseBean {
private String host;
private Integer port;
private String userName;
private String password;
    private String ftpSeperator;
    private String ftpPath="";
private int repeatTime = 0;//连接ftp服务器的次数

public String getHost() {
return host;
}

public void setHost(String host) {
this.host = host;
}


public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}


public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}


public void setFtpSeperator(String ftpSeperator) {
this.ftpSeperator = ftpSeperator;
}


public String getFtpSeperator() {
return ftpSeperator;
}


public void setFtpPath(String ftpPath) {
if(ftpPath!=null)
this.ftpPath = ftpPath;
}


public String getFtpPath() {
return ftpPath;
}


public void setRepeatTime(int repeatTime) {
if (repeatTime > 0)
this.repeatTime = repeatTime;
}


public int getRepeatTime() {
return repeatTime;
}


/**
* take an example:<br>
* ftp://userName:password@ip:port/ftpPath/
* @return 
*/
public String getFTPURL() {
StringBuffer buf = new StringBuffer();
buf.append("ftp://");
buf.append(getUserName());
buf.append(":");
buf.append(getPassword());
buf.append("@");
buf.append(getHost());
buf.append(":");
buf.append(getPort());
buf.append("/");
buf.append(getFtpPath());
 
return buf.toString();
}
}
2、导入包commons-net-1.4.1.jar

package com.util;


import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.SocketException;
import java.net.URL;
import java.net.URLConnection;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;


import com.bean.FtpUseBean;


public class FtpUtil extends FTPClient {


private static Log log = LogFactory.getLog(FtpUtil.class);
private FtpUseBean ftpUseBean;
//获取目标路径下的文件属性信息,主要是获取文件的size
private FTPFile[] files;

public FtpUseBean getFtpUseBean() {
return ftpUseBean;
}




public FtpUtil(){
super();
}


public void setFtpUseBean(FtpUseBean ftpUseBean) {
this.ftpUseBean = ftpUseBean;
}

public boolean ftpLogin() {
boolean isLogined = false;
try {
log.debug("ftp login start ...");
int repeatTime = ftpUseBean.getRepeatTime();
for (int i = 0; i < repeatTime; i++) {
super.connect(ftpUseBean.getHost(), ftpUseBean.getPort());
isLogined = super.login(ftpUseBean.getUserName(), ftpUseBean.getPassword());
if (isLogined)
break;
}
if(isLogined)
log.debug("ftp login successfully ...");
else
log.debug("ftp login failed ...");
return isLogined;
} catch (SocketException e) {
log.error("", e);
return false;
} catch (IOException e) {
log.error("", e);
return false;
} catch (RuntimeException e) {
log.error("", e);
return false;
}
}


public void setFtpToUtf8() throws IOException {


FTPClientConfig conf = new FTPClientConfig();
super.configure(conf);
super.setFileType(FTP.IMAGE_FILE_TYPE);
int reply = super.sendCommand("OPTS UTF8 ON");
if (reply == 200) { // UTF8 Command
super.setControlEncoding("UTF-8");
}


}


public void close() {
if (super.isConnected()) {
try {
super.logout();
super.disconnect();
log.debug("ftp logout ....");
} catch (Exception e) {
log.error(e.getMessage());
throw new RuntimeException(e.toString());
}
}
}


public void uploadFileToFtpByIS(InputStream inputStream, String fileName) throws IOException {
super.storeFile(ftpUseBean.getFtpPath()+fileName, inputStream);
}


public File downFtpFile(String fileName, String localFileName) throws IOException {
File outfile = new File(localFileName);
OutputStream oStream = null;
try {
oStream = new FileOutputStream(outfile);
super.retrieveFile(ftpUseBean.getFtpPath()+fileName, oStream);
return outfile;
} finally {
if (oStream != null)
oStream.close();
}
}




public FTPFile[] listFtpFiles() throws IOException {
return super.listFiles(ftpUseBean.getFtpPath());
}


public void deleteFtpFiles(FTPFile[] ftpFiles) throws IOException {
String path = ftpUseBean.getFtpPath();
for (FTPFile ff : ftpFiles) {
if (ff.isFile()) {
if (!super.deleteFile(path + ff.getName()))
throw new RuntimeException("delete File" + ff.getName() + " is n't seccess");
}
}
}


public void deleteFtpFile(String fileName) throws IOException {
if (!super.deleteFile(ftpUseBean.getFtpPath() +fileName))
throw new RuntimeException("delete File" + ftpUseBean.getFtpPath() +fileName + " is n't seccess");
}


public InputStream downFtpFile(String fileName) throws IOException {
return super.retrieveFileStream(ftpUseBean.getFtpPath()+fileName);
}


/**

* @return
* @return StringBuffer
* @description 下载ftp服务器上的文件,addr为带用户名和密码的URL
*/
public StringBuffer downloadBufferByURL(String addr) {
BufferedReader in = null;
try {
URL url = new URL(addr);
URLConnection conn = url.openConnection();
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
StringBuffer ret = new StringBuffer();
while ((line = in.readLine()) != null)
ret.append(line);

return ret;
} catch (Exception e) {
log.error(e);
return null;
} finally {
try {
if (null != in)
in.close();
} catch (IOException e) {
e.printStackTrace();
log.error(e);
}
}
}


/**

* @return
* @return byte[]
* @description 下载ftp服务器上的文件,addr为带用户名和密码的URL
*/
public byte[] downloadByteByURL(String addr) {

FTPClient ftp = null;

try {

URL url = new URL(addr);

int port = url.getPort()!=-1?url.getPort():21;
log.info("HOST:"+url.getHost());
log.info("Port:"+port);
log.info("USERINFO:"+url.getUserInfo());
log.info("PATH:"+url.getPath());

ftp = new FTPClient();

ftp.setDataTimeout(30000);
ftp.setDefaultTimeout(30000);
ftp.setReaderThread(false);
ftp.connect(url.getHost(), port);
ftp.login(url.getUserInfo().split(":")[0], url.getUserInfo().split(":")[1]);
FTPClientConfig conf = new FTPClientConfig("UNIX");   
                 ftp.configure(conf); 
log.info(ftp.getReplyString());

ftp.enterLocalPassiveMode(); //ftp.enterRemotePassiveMode() 
ftp.setFileTransferMode(FTP.STREAM_TRANSFER_MODE); 


int reply = ftp.sendCommand("OPTS UTF8 ON");// try to

log.debug("alter to utf-8 encoding - reply:" + reply);
if (reply == 200) { // UTF8 Command
ftp.setControlEncoding("UTF-8");
}
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);


log.info(ftp.getReplyString());

ByteArrayOutputStream out=new ByteArrayOutputStream();
                 DataOutputStream o=new DataOutputStream(out);
                 String remotePath = url.getPath();
                 /**
                 * Fixed:if doen't remove the first "/" at the head of url,
                  * the file can't be retrieved.
                 */
                if(remotePath.indexOf("/")==0) {
                 remotePath = url.getPath().replaceFirst("/", "");
                }
                ftp.retrieveFile(remotePath, o);        
byte[] ret = out.toByteArray();
o.close();

String filepath = url.getPath();
ftp.changeWorkingDirectory(filepath.substring(0,filepath.lastIndexOf("/")));
files = ftp.listFiles();

return ret;
      } catch (Exception ex) {
log.error("Failed to download file from ["+addr+"]!"+ex);
     } finally {
try {
if (null!=ftp)
ftp.disconnect();
} catch (Exception e) {
//
}
}
return null;
// StringBuffer buffer = downloadBufferByURL(addr);
// return null == buffer ? null : buffer.toString().getBytes();
}




public FTPFile[] getFiles() {
return files;
}




public void setFiles(FTPFile[] files) {
this.files = files;
}




// public static void getftpfilesize(String addr){
//
// FTPClient ftp = null;
//
// try {
//
// URL url = new URL(addr);
//
// int port = url.getPort()!=-1?url.getPort():21;
// log.info("HOST:"+url.getHost());
// log.info("Port:"+port);
// log.info("USERINFO:"+url.getUserInfo());
// log.info("PATH:"+url.getPath());
//
// ftp = new FTPClient();
//
// ftp.setDataTimeout(30000);
// ftp.setDefaultTimeout(30000);
// ftp.setReaderThread(false);
// ftp.connect(url.getHost(), port);
// ftp.login(url.getUserInfo().split(":")[0], url.getUserInfo().split(":")[1]);
// FTPClientConfig conf = new FTPClientConfig("UNIX");   
//        ftp.configure(conf); 
// log.info(ftp.getReplyString());
//
// ftp.enterLocalPassiveMode(); //ftp.enterRemotePassiveMode() 
// ftp.setFileTransferMode(FTP.STREAM_TRANSFER_MODE); 
//
// int reply = ftp.sendCommand("OPTS UTF8 ON");// try to
//
// log.debug("alter to utf-8 encoding - reply:" + reply);
// if (reply == 200) { // UTF8 Command
// ftp.setControlEncoding("UTF-8");
// }
// ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
// ftp.changeWorkingDirectory(url.getPath());
// FTPFile[] files = ftp.listFiles();
// for (FTPFile flie : files){
// System.out.println(new String(flie.getName().getBytes("gbk"),"ISO8859-1"));
// System.out.println(flie.getSize());
// }
//
//
// } catch (Exception ex) {
// log.error("Failed to download file from ["+addr+"]!"+ex);
// } finally {
// try {<pre class="java" name="code"> if (null!=ftp)
// ftp.disconnect();
 // } catch (Exception e) {
}
}
}
}</pre>
<pre></pre>
   

转自:http://blog.csdn.net/jzhf2012/article/details/8455044

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用 sun.net.ftp.ftpclient 工具类进行文件上传需要以下步骤: 1. 建立 FTP 连接:使用 `FtpClient` 类的 `openServer` 方法建立连接,需要传入 FTP 服务器的地址和端口号。 2. 登录 FTP 服务器:使用 `FtpClient` 类的 `login` 方法登录 FTP 服务器,需要传入 FTP 服务器的用户名和密码。 3. 切换到上传目录:使用 `FtpClient` 类的 `cd` 方法切换到上传目录。 4. 设置上传模式:使用 `FtpClient` 类的 `setBinaryMode` 方法设置上传模式为二进制模式。 5. 上传文件:使用 `FtpClient` 类的 `put` 方法上传文件,需要传入本地文件的路径和上传后的文件名。 6. 关闭连接:使用 `FtpClient` 类的 `closeServer` 方法关闭连接。 以下是一个简单的上传文件的示例代码: ```java import sun.net.ftp.FtpClient; import java.io.FileInputStream; public class FtpUploader { public static void main(String[] args) throws Exception { String server = "ftp.example.com"; int port = 21; String username = "username"; String password = "password"; String localFilePath = "/path/to/local/file.txt"; String remoteFileName = "file.txt"; FtpClient ftpClient = new FtpClient(server, port); ftpClient.login(username, password); ftpClient.cd("/upload"); ftpClient.setBinaryMode(); FileInputStream fis = new FileInputStream(localFilePath); ftpClient.put(fis, remoteFileName); fis.close(); ftpClient.closeServer(); } } ``` 注意:`sun.net.ftp.FtpClient` 类是 Sun JDK 内部使用的类,不是公开的 API,因此可能会在不同版本的 JDK 存在变化。建议使用第三方 FTP 客户端库,如 Apache Commons Net,来进行 FTP 操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值