如何用java代码实现ftp文件上传

如何用java代码实现ftp文件上传,第1张

import java.io.File

import java.io.FileInputStream

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

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

public class test {

private FTPClient ftp

/**

*

* @param path 上传到ftp服务器哪个路径

* @param addr 地址

* @param port 端口号

* @param username 用户名

* @param password 密码

* @return

* @throws Exception

*/

private boolean connect(String path,String addr,int port,String username,String password) throws Exception {

boolean result = false

ftp = new FTPClient()

int reply

ftp.connect(addr,port)

ftp.login(username,password)

ftp.setFileType(FTPClient.BINARY_FILE_TYPE)

reply = ftp.getReplyCode()

if (!FTPReply.isPositiveCompletion(reply)) {

ftp.disconnect()

return result

}

ftp.changeWorkingDirectory(path)

result = true

return result

}

/**

*

* @param file 上传的文件或文件夹

* @throws Exception

*/

private void upload(File file) throws Exception{

if(file.isDirectory()){

ftp.makeDirectory(file.getName())

ftp.changeWorkingDirectory(file.getName())

String[] files = file.list()

for (int i = 0i <files.lengthi++) {

File file1 = new File(file.getPath()+"\\"+files[i] )

if(file1.isDirectory()){

upload(file1)

ftp.changeToParentDirectory()

}else{

File file2 = new File(file.getPath()+"\\"+files[i])

package com.quantongfu.ftp.ftp

import java.io.File

import java.io.FileInputStream

import java.io.IOException

import java.net.ServerSocket

import java.util.List

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

import org.apache.log4j.Logger

import org.apache.log4j.net.SocketServer

import com.quantongfu.conf.FtpConf

/**

 * @项目名称: telinSyslog

 * @文件名称: Ftp.java

 * @创建日期:2015年9月14日 下午3:22:08

 * @功能描述:ftp实体类,用于连接,上传

 * @修订记录:

 */

public class Ftp {

    private static Logger logger = Logger.getLogger(Ftp.class)

    private FTPClient ftp

    /**

     * 

     * @param path

     *            上传到ftp服务器哪个路径下

     * @param addr

     *            地址

     * @param port

     *            端口号

     * @param username

     *            用户名

     * @param password

     *            密码

     * @return

     * @throws Exception

     */

    public boolean connect() throws Exception {

        boolean result = false

        ftp = new FTPClient()

        int reply

        ftp.connect(FtpConf.FTP_HOST, FtpConf.FTP_PORT)

        ftp.login(FtpConf.FTP_USER_NAME, FtpConf.FTP_PASSWORD)

        ftp.setFileType(FTPClient.BINARY_FILE_TYPE)

        ftp.setDataTimeout(60000)

        reply = ftp.getReplyCode()

        if (!FTPReply.isPositiveCompletion(reply)) {

            ftp.disconnect()

            return result

        }

        if (FtpConf.IS_FTP_DIRECTORY) {

            ftp.changeWorkingDirectory(FtpConf.FTP_DIRECTORY)

        }

        result = true

        return result

    }

    /**

     * 

     * @param files

     *            上传的文件

     * @throws Exception

     */

    public boolean upload(File file) throws IOException {

        FileInputStream input = null

        try {

            input = new FileInputStream(file)

            boolean b = ftp.storeFile(file.getName() + ".tmp", input)

            if (b) {

                b = ftp.rename(file.getName() + ".tmp", file.getName())

            }

            return b

        } catch (Exception e) {

            e.printStackTrace()

            return false

        } finally {

            if (input != null) {

                input.close()

            }

        }

    }

    /**

     * 

     * @param files

     *            上传的文件

     * @throws Exception

     */

    public boolean upload(ServerSocket server, File file) throws Exception {

        FileInputStream input = null

        try {

            if (!file.exists()) {

                return true

            }

            input = new FileInputStream(file)

            boolean b = ftp.storeFile(server, file.getName() + ".tmp", input)

            if (b) {

                b = ftp.rename(file.getName() + ".tmp", file.getName())

                if (b) {

                    file.delete()

                }

            }

            return b

        } catch (Exception e) {

            logger.error("ftp error" + e.getMessage())

            return false

        } finally {

            if (input != null) {

                try {

                    input.close()

                } catch (IOException e) {

                    e.printStackTrace()

                }

            }

        }

    }

        /*断开连接*/

    public void disConnect() {

        try {

            if (ftp != null) {

                ftp.disconnect()

            }

        } catch (IOException e) {

            e.printStackTrace()

        }

    }

        /*获取连接*/

    public static Ftp getFtp() {

        Ftp ftp = new Ftp()

        try {

            ftp.connect()

        } catch (Exception e) {

            logger.error("FTP连接异常" + e.getMessage())

            e.printStackTrace()

        }

        return ftp

    }

        /*重连*/

    public Ftp reconnect() {

        disConnect()

        return getFtp()

    }

}

使用Apache FtpClient jar包,获取jar : http://commons.apache.org/net/

现在已经封装好了的方法,不需要任何其他知识即可连接的。只需要知道ftp登录用户名、密码、端口、存储路径即可。

package zn.ccfccb.util

import hkrt.b2b.view.util.Log

import hkrt.b2b.view.util.ViewUtil

import java.io.ByteArrayOutputStream

import java.io.FileInputStream

import java.io.FileOutputStream

import java.io.InputStream

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

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

public class CCFCCBFTP {

/**

* 上传文件

*

* @param fileName

* @param plainFilePath 明文文件路径路径

* @param filepath

* @return

* @throws Exception

*/

public static String fileUploadByFtp(String plainFilePath, String fileName, String filepath) throws Exception {

FileInputStream fis = null

ByteArrayOutputStream bos = null

FTPClient ftpClient = new FTPClient()

String bl = "false"

try {

fis = new FileInputStream(plainFilePath)

bos = new ByteArrayOutputStream(fis.available())

byte[] buffer = new byte[1024]

int count = 0

while ((count = fis.read(buffer)) != -1) {

bos.write(buffer, 0, count)

}

bos.flush()

Log.info("加密上传文件开始")

Log.info("连接远程上传服务器"+CCFCCBUtil.CCFCCBHOSTNAME+":"+22)

ftpClient.connect(CCFCCBUtil.CCFCCBHOSTNAME, 22)

ftpClient.login(CCFCCBUtil.CCFCCBLOGINNAME, CCFCCBUtil.CCFCCBLOGINPASSWORD)

//Log.info("连接远程上传服务器"+"192.168.54.106:"+2021)

//ftpClient.connect("192.168.54.106", 2021)

//ftpClient.login("hkrt-CCFCCBHK", "3OLJheziiKnkVcu7Sigz")

FTPFile[] fs

fs = ftpClient.listFiles()

for (FTPFile ff : fs) {

if (ff.getName().equals(filepath)) {

bl="true"

ftpClient.changeWorkingDirectory("/"+filepath+"")

}

}

Log.info("检查文件路径是否存在:/"+filepath)

if("false".equals(bl)){

ViewUtil.dataSEErrorPerformedCommon( "查询文件路径不存在:"+"/"+filepath)

return bl

}

ftpClient.setBufferSize(1024)

ftpClient.setControlEncoding("GBK")

// 设置文件类型(二进制)

ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE)

ftpClient.storeFile(fileName, fis)

Log.info("上传文件成功:"+fileName+"。文件保存路径:"+"/"+filepath+"/")

return bl

} catch (Exception e) {

throw e

} finally {

if (fis != null) {

try {

fis.close()

} catch (Exception e) {

Log.info(e.getLocalizedMessage(), e)

}

}

if (bos != null) {

try {

bos.close()

} catch (Exception e) {

Log.info(e.getLocalizedMessage(), e)

}

}

}

}

/**

*下载并解压文件

*

* @param localFilePath

* @param fileName

* @param routeFilepath

* @return

* @throws Exception

*/

public static String fileDownloadByFtp(String localFilePath, String fileName,String routeFilepath) throws Exception {

FileInputStream fis = null

ByteArrayOutputStream bos = null

FileOutputStream fos = null

FTPClient ftpClient = new FTPClient()

String SFP = System.getProperty("file.separator")

String bl = "false"

try {

Log.info("下载并解密文件开始")

Log.info("连接远程下载服务器"+CCFCCBUtil.CCFCCBHOSTNAME+":"+22)

ftpClient.connect(CCFCCBUtil.CCFCCBHOSTNAME, 22)

ftpClient.login(CCFCCBUtil.CCFCCBLOGINNAME, CCFCCBUtil.CCFCCBLOGINPASSWORD)

//ftpClient.connect(CMBCUtil.CMBCHOSTNAME, 2021)

//ftpClient.login(CMBCUtil.CMBCLOGINNAME, CMBCUtil.CMBCLOGINPASSWORD)

FTPFile[] fs

ftpClient.makeDirectory(routeFilepath)

ftpClient.changeWorkingDirectory(routeFilepath)

bl = "false"

fs = ftpClient.listFiles()

for (FTPFile ff : fs) {

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

bl = "true"

Log.info("下载文件开始。")

ftpClient.setBufferSize(1024)

// 设置文件类型(二进制)

ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE)

InputStream is = ftpClient.retrieveFileStream(fileName)

bos = new ByteArrayOutputStream(is.available())

byte[] buffer = new byte[1024]

int count = 0

while ((count = is.read(buffer)) != -1) {

bos.write(buffer, 0, count)

}

bos.flush()

fos = new FileOutputStream(localFilePath+SFP+fileName)

fos.write(bos.toByteArray())

Log.info("下载文件结束:"+localFilePath)

}

}

Log.info("检查文件是否存:"+fileName+" "+bl)

if("false".equals(bl)){

ViewUtil.dataSEErrorPerformedCommon("查询无结果,请稍后再查询。")

return bl

}

return bl

} catch (Exception e) {

throw e

} finally {

if (fis != null) {

try {

fis.close()

} catch (Exception e) {

Log.info(e.getLocalizedMessage(), e)

}

}

if (bos != null) {

try {

bos.close()

} catch (Exception e) {

Log.info(e.getLocalizedMessage(), e)

}

}

if (fos != null) {

try {

fos.close()

} catch (Exception e) {

Log.info(e.getLocalizedMessage(), e)

}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/tougao/12084659.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-20
下一篇2023-05-20

发表评论

登录后才能评论

评论列表(0条)

    保存