java实现ftp上传下载

代码如下

<span style="font-size:18px;">import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.FileWriter;

import java.io.IOException;

import java.io.InputStream;

import java.util.Arrays;

import java.util.List;

import org.apache.commons.net.ftp.FTPClient;

import org.apache.commons.net.ftp.FTPClientConfig;

import org.apache.commons.net.ftp.FTPFile;

import org.apache.commons.net.ftp.FTPListParseEngine;

import org.apache.commons.net.ftp.FTPReply;

import org.dom4j.Document;

import org.dom4j.DocumentHelper;

import org.dom4j.Element;

import org.dom4j.io.OutputFormat;

import org.dom4j.io.XMLWriter;

public class FtpHelper {

private FTPClient ftp = null;

/**

 * Ftp服务器

 */

private String server;

/**

 * 用户名

 */

private String uname;

/**

 * 密码

 */

private String password;

/**

 * 连接端口,默认21

 */

private int port = 21;

private Document document ;

public FtpHelper(String server, int port, String uname,

String password){

this.server = server;

if (this.port > 0){

this.port = port;

}

this.uname = uname;

this.password = password;

//初始化

ftp = new FTPClient();

}

/**

 * 连接FTP服务器

 * 

 * @param server

 * @param uname

 * @param password

 * @return

 * @throws Exception

 */

public FTPClient connectFTPServer() throws Exception {

try {

ftp.configure(getFTPClientConfig());

ftp.connect(this.server, this.port);

if (!ftp.login(this.uname, this.password)) {

ftp.logout();

ftp = null;

return ftp;

}

// 文件类型,默认是ASCII

ftp.setFileType(FTPClient.BINARY_FILE_TYPE);

ftp.setControlEncoding("GBK");

// 设置被动模式

ftp.enterLocalPassiveMode();

//ftp.setConnectTimeout(2000);

ftp.setBufferSize(1024);

// 响应信息

int replyCode = ftp.getReplyCode();

if ((!FTPReply.isPositiveCompletion(replyCode))) {

// 关闭Ftp连接

closeFTPClient();

// 释放空间

ftp = null;

throw new Exception("登录FTP服务器失败,请检查![Server:" + server + "、"

+ "User:" + uname + "、" + "Password:" + password);

} else {

return ftp;

}

} catch (Exception e) {

ftp.disconnect();

ftp = null;

throw e;

}

}

/**

 * 配置FTP连接参数

 * 

 * @return

 * @throws Exception

 */

public FTPClientConfig getFTPClientConfig() throws Exception {

String systemKey = FTPClientConfig.SYST_NT;

String serverLanguageCode = "zh";

FTPClientConfig conf = new FTPClientConfig(systemKey);

conf.setServerLanguageCode(serverLanguageCode);

conf.setDefaultDateFormatStr("yyyy-MM-dd");

return conf;

}

/**

 * 向FTP根目录上传文件

 * 

 * @param localFile

 * @param newName

 *            新文件名

 * @throws Exception

 */

public Boolean uploadFile(String localFile, String newName)

throws Exception {

InputStream input = null;

boolean success = false;

try {

File file = null;

if (checkFileExist(localFile)) {

file = new File(localFile);

}

input = new FileInputStream(file);

success = ftp.storeFile(newName, input);

if (!success) {

throw new Exception("文件上传失败!");

}

} catch (Exception e) {

throw e;

} finally {

if (input != null) {

input.close();

}

}

return success;

}

/**

 * 向FTP根目录上传文件

 * 

 * @param input

 * @param newName

 *            新文件名

 * @throws Exception

 */

public Boolean uploadFile(InputStream input, String newName)

throws Exception {

boolean success = false;

try {

success = ftp.storeFile(newName, input);

if (!success) {

throw new Exception("文件上传失败!");

}

} catch (Exception e) {

throw e;

} finally {

if (input != null) {

input.close();

}

}

return success;

}

/**

 * 向FTP指定路径上传文件

 * 

 * @param localFile

 * @param newName

 *            新文件名

 * @param remoteFoldPath

 * @throws Exception

 */

public Boolean uploadFile(String localFile, String newName,

String remoteFoldPath) throws Exception {

InputStream input = null;

boolean success = false;

try {

File file = null;

if (checkFileExist(localFile)) {

file = new File(localFile);

}

input = new FileInputStream(file);

// 改变当前路径到指定路径

if (!this.changeDirectory(remoteFoldPath)) {

System.out.println("服务器路径不存!");

return false;

}

success = ftp.storeFile(newName, input);

if (!success) {

throw new Exception("文件上传失败!");

}

} catch (Exception e) {

throw e;

} finally {

if (input != null) {

input.close();

}

}

return success;

}

/**

 * 向FTP指定路径上传文件

 * 

 * @param input

 * @param newName

 *            新文件名

 * @param remoteFoldPath

 * @throws Exception

 */

public Boolean uploadFile(InputStream input, String newName,

String remoteFoldPath) throws Exception {

boolean success = false;

try {

// 改变当前路径到指定路径

if (!this.changeDirectory(remoteFoldPath)) {

System.out.println("服务器路径不存!");

return false;

}

success = ftp.storeFile(newName, input);

if (!success) {

throw new Exception("文件上传失败!");

}

} catch (Exception e) {

throw e;

} finally {

if (input != null) {

input.close();

}

}

return success;

}

/**

 * 从FTP服务器下载文件

 * 

 * @param remotePath

 *            FTP路径(不包含文件名)

 * @param fileName

 *            下载文件名

 * @param localPath

 *            本地路径

 */

public Boolean downloadFile(String remotePath, String fileName,

String localPath) throws Exception {

BufferedOutputStream output = null;

boolean success = false;

try {

// 检查本地路径

this.checkFileExist(localPath);

// 改变工作路径

if (!this.changeDirectory(remotePath)) {

System.out.println("服务器路径不存在");

return false;

}

// 列出当前工作路径下的文件列表

List<FTPFile> fileList = this.getFileList();

if (fileList == null || fileList.size() == 0) {

System.out.println("服务器当前路径下不存在文件!");

return success;

}

for (FTPFile ftpfile : fileList) {

if (ftpfile.getName().equals(fileName)) {

File localFilePath = new File(localPath + File.separator

+ ftpfile.getName());

output = new BufferedOutputStream(new FileOutputStream(

localFilePath));

success = ftp.retrieveFile(ftpfile.getName(), output);

}

}

if (!success) {

throw new Exception("文件下载失败!");

}

} catch (Exception e) {

throw e;

} finally {

if (output != null) {

output.close();

}

}

return success;

}

/**

 * 从FTP服务器获取文件流

 * 

 * @param remoteFilePath

 * @return

 * @throws Exception

 */

public InputStream downloadFile(String remoteFilePath) throws Exception {

return ftp.retrieveFileStream(remoteFilePath);

}

/**

 * 获取FTP服务器上指定路径下的文件列表

 * 

 * @param filePath

 * @return

 */

public List<FTPFile> getFtpServerFileList(String remotePath)

throws Exception {

FTPListParseEngine engine = ftp.initiateListParsing(remotePath);

List<FTPFile> ftpfiles = Arrays.asList(engine.getNext(25));

return ftpfiles;

}

/**

 * 获取FTP服务器上[指定路径]下的文件列表

 * 

 * @param path

 * @return

 * @throws Exception

 */

public List<FTPFile> getFileList(String remotePath) throws Exception {

List<FTPFile> ftpfiles = Arrays.asList(ftp.listFiles(remotePath));

return ftpfiles;

}

/**

 * 获取FTP服务器[当前工作路径]下的文件列表

 * 

 * @param path

 * @return

 * @throws Exception

 */

public List<FTPFile> getFileList() throws Exception {

List<FTPFile> ftpfiles = Arrays.asList(ftp.listFiles());

return ftpfiles;

}

/**

 * 改变FTP服务器工作路径 

 * 

 * @param remoteFoldPath

 */

public Boolean changeDirectory(String remoteFoldPath) throws Exception {

return ftp.changeWorkingDirectory(remoteFoldPath);

}

/**

 * 删除文件

 * 

 * @param remoteFilePath

 * @return

 * @throws Exception

 */

public Boolean deleteFtpServerFile(String remoteFilePath) throws Exception {

return ftp.deleteFile(remoteFilePath);

}

/**

 * 创建目录

 * 

 * @param remoteFoldPath

 * @return

 */

public boolean createFold(String remoteFoldPath) throws Exception {

boolean flag = ftp.makeDirectory(remoteFoldPath);

if (!flag) {

throw new Exception("创建目录失败");

}

return false;

}

/**

 * 删除目录

 * @param remoteFoldPath

 * @return

 * @throws Exception

 */

public boolean deleteFold(String remoteFoldPath) throws Exception {

return ftp.removeDirectory(remoteFoldPath) ;

}

/**

 * 删除目录以及文件

 * 

 * @param remoteFoldPath

 * @return

 */

public boolean deleteFoldAndsubFiles(String remoteFoldPath)

throws Exception {

boolean success = false;

List<FTPFile> list = this.getFileList(remoteFoldPath);

if (list == null || list.size() == 0) {

return deleteFold(remoteFoldPath);

}

for (FTPFile ftpFile : list) {

String name = ftpFile.getName();

if (ftpFile.isDirectory()) {

success = deleteFoldAndsubFiles(remoteFoldPath + "/" + name);

if (!success)

break;

} else {

success = deleteFtpServerFile(remoteFoldPath + "/" + name);

if (!success)

break;

}

}

if (!success)

return false;

success = deleteFold(remoteFoldPath);

return success;

}

/**

 * 检查本地路径是否存在

 * 

 * @param filePath

 * @return

 * @throws Exception

 */

public boolean checkFileExist(String filePath) throws Exception {

boolean flag = false;

File file = new File(filePath);

if (!file.exists()) {

throw new Exception("本地路径不存在,请检查!");

} else {

flag = true;

}

return flag;

}

/**

 * 创建XML文件

 * @return

 */

public Element getCurrentElement(){

document = DocumentHelper.createDocument();

return document.addElement("root");

}

/**

 * 生成目录XML文件

 */

public void createDirectoryXML(String remotePath,Element fatherElement) throws Exception{

List<FTPFile> list = this.getFileList();

for(FTPFile ftpfile:list){

Element currentElement = fatherElement; //当前的目录节点

String newRemotePath = remotePath+ftpfile.getName();

if(ftpfile.isDirectory()){

Element dirElement = fatherElement.addElement("dir") ;

dirElement.addAttribute("name",ftpfile.getName());

currentElement = dirElement;

this.changeDirectory(newRemotePath); //从根目录开始

createDirectoryXML(newRemotePath,dirElement);

}else{

 Element fileElement = fatherElement.addElement("file");//文件节点

 fileElement.setText(ftpfile.getName()) ;

}

}

}

/**

 * 保存xml

 */

public void saveXML(){

XMLWriter output = new XMLWriter();

        //输出格式化

        OutputFormat format = OutputFormat.createPrettyPrint();

        try {

            output = new XMLWriter(new FileWriter("src/com/shine/Ftp/config/dir.xml"), format);

            output.write(this.document);

            output.close();

        } catch (IOException e) {

            e.printStackTrace();

        }

}

/**

 * 关闭FTP连接

 * 

 * @param ftp

 * @throws Exception

 */

public void closeFTPClient(FTPClient ftp) throws Exception {

try {

if (ftp.isConnected())

ftp.logout();

ftp.disconnect();

} catch (Exception e) {

throw new Exception("关闭FTP服务出错!");

}

}

/**

 * 关闭FTP连接

 * 

 * @throws Exception

 */

public void closeFTPClient() throws Exception {

this.closeFTPClient(this.ftp);

}

/**

 * Get Attribute Method

 * 

 */

public FTPClient getFtp() {

return ftp;

}

public String getServer() {

return server;

}

public String getUname() {

return uname;

}

public String getPassword() {

return password;

}

public int getPort() {

return port;

}

/**

 * Set Attribute Method

 * 

 */

public void setFtp(FTPClient ftp) {

this.ftp = ftp;

}

public void setServer(String server) {

this.server = server;

}

public void setUname(String uname) {

this.uname = uname;

}

public void setPassword(String password) {

this.password = password;

}

public void setPort(int port) {

this.port = port;

}

/**

 * 主方法(测试)

 * 

 * 问题:上传时命名的新文件名不能有中文,否则上传失败.

 * 

 * @param args

 */

public static void main(String[] args) {

try {

FtpHelper fu = new FtpHelper("192.168.2.18", 21, "administrator","sunshine");

fu.connectFTPServer();

Element fatherElement = fu.getCurrentElement();

fu.createDirectoryXML("/", fatherElement);

fu.saveXML();

} catch (Exception e) {

System.out.println("异常信息:" + e.getMessage());

}

}

}</span>

注:详细信息尽在java教程网

时间: 2024-10-09 22:35:14

java实现ftp上传下载的相关文章

Java实现FTP上传下载功能

Java FTP客户端工具包很多,在此我选用的Apache的FTPClient.这个包的获取可以通过http://commons.apache.org/net/来获取,我使用的是最新的commons-net-1.4.1.zip.其中包含了众多的java网络编程的工具包,官方文档列举如下: 1.支持网络协议如下: FTP.NNTP. SMTP.POP3.Telnet.TFTP.Finger.Whois.rexec/rcmd/rlogin.Time (rdate) and Daytime.Echo.

Java 利用FTP上传,下载文件,遍历文件目录

Java实现FTP上传下载文件的工具包有很多,这里我采用Java自带的API,实现FTP上传下载文件.另外JDK1.7以前的版本与其之后版本的API有了较大的改变了. 例如: JDK1.7之前 JDK1.7 ftpClient = new FtpClinet() ftpClient = FtpClient.create(ip) ftpclient.login(user,password) ftpclient.login(user,null,password) ftpclient.binary()

简单的FTP上传下载(java实现)

/** *阅读前请自己在win7上建立FTP主机 *具体步骤如:http://jingyan.baidu.com/article/574c5219d466c36c8d9dc138.html * 然后将以下FTP,username,password分别改成你的FTP ip地址 用户名 密码即可 * 本例子用了apche的commons-net-3.3.jar以方便FTP的访问 请手动buid -path * 待完成版 刷新按钮 登录 都还没有做 而且上传 下载 完成后都需要重新运行 * 2014-

java做的比较完善的FTP上传下载文件服务器源码

Filename: ftp.java Author: leetsing(elove) Create date: 2004-08-30 Use: connect to FTP server,then upload and download file Modify date: 2004-09-05 add to upload file 2004-09-13 add to download file Copy right: Magisky Media Technology Co.,Ltd. *****

java ftp 上传下载工具类

1 package com.mohecun.utils; 2 3 import java.io.File; 4 import java.io.FileInputStream; 5 import java.io.FileNotFoundException; 6 import java.io.FileOutputStream; 7 import java.io.IOException; 8 import java.io.InputStream; 9 import java.io.OutputStre

java ftp上传下载

/** * Description: 从FTP服务器下载文件 * @param url FTP服务器hostname * @param port FTP服务器端口 * @param username FTP登录账号 * @param password FTP登录密码 * @param remotePath FTP服务器上的相对路径 * @param fileName 要下载的文件名 * @param localPath 下载后保存到本地的路径 * @return */ public static

FTP 上传下载工具类

import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.SocketException; import o

高可用的Spring FTP上传下载工具类(已解决上传过程常见问题)

前言 最近在项目中需要和ftp服务器进行交互,在网上找了一下关于ftp上传下载的工具类,大致有两种. 第一种是单例模式的类. 第二种是另外定义一个Service,直接通过Service来实现ftp的上传下载. 这两种感觉都有利弊. 第一种实现了代码复用,但是配置信息全需要写在类中,维护比较复杂. 第二种如果是spring框架,可以通过propertis文件,动态的注入配置信息,但是又不能代码复用. 所以我打算自己实现一个工具类,来把上面的两种优点进行整合.顺便把一些上传过程中一些常见的问题也给解

python之实现ftp上传下载代码(含错误处理)

# -*- coding: utf-8 -*- #python 27 #xiaodeng #python之实现ftp上传下载代码(含错误处理) #http://www.cnblogs.com/kaituorensheng/p/4480512.html#_label2 import ftplib import socket import os def ftpconnect(ftp_info): try: ftp = ftplib.FTP(ftp_info[0]) except (socket.er