---
title: "java连接ftp上传"
author: "java_script"
date: "2011-04-19T08:42:12Z"
tags: ["F#", "Java"]
categories: ["编程语言"]
slug: "java-ftp"
draft: false
lastmod: "2011-04-19T08:42:12Z"
id: 1007609
url: "https://java-script.iteye.com/blog/1007609"
---

/**
	 * 利用ftp把handlepath路径里面的文件都上传上去，上传完后删除掉。
	 * @param handlePath
	 */
	private void ftpUpload(String handlePath) {
		FTPClient ftp = new FTPClient();
		try {
			/*Properties properties = new Properties();
			properties.load(CpsUploadFileAction.class.getClassLoader().getResourceAsStream("/config/ftpconfig.properties"));*/
			Properties properties = FtpConfigUtil.getInstance().getFtpConfigProp();
			ftp.connect(properties.getProperty(FtpConfigUtil.FTPSERVERIP), Integer.parseInt(properties.getProperty(FtpConfigUtil.FTPSERVERPORT)));//连接ftp
			ftp.login(properties.getProperty(FtpConfigUtil.USERNAME), properties.getProperty(FtpConfigUtil.PASSWORD));//登录ftp
			ftp.makeDirectory(properties.getProperty(FtpConfigUtil.PATHNAME));//创建目录;
			ftp.changeWorkingDirectory(properties.getProperty(FtpConfigUtil.PATHNAME));
			File f = new File(handlePath);
			File loadFiles = f.listFiles();
			//把文件传送到服务器上;
			for(int i=0;i<loadFiles.length;i++) {
				File loadFile = loadFiles*;
				if(loadFile.isDirectory()) {
					continue;
				}
				if(loadFile.isFile()) {
					InputStream in = new FileInputStream(loadFile);
					ftp.storeFile(loadFile.getName(), in);
					in.close();
				}
				
			}
			ftp.logout();//退出连接
		} catch(IOException ioe) {
			ioe.printStackTrace();
			throw new RuntimeException(ioe.getMessage(),ioe);
		} finally {
			if(ftp.isConnected()) {
				try {
					ftp.disconnect();//关闭连接
				} catch (IOException e) {
					e.printStackTrace();
					throw new RuntimeException(e.getMessage(),e);
				}
			}
		}
		//删除handlePath底下的文件;
		File f = new File(handlePath);
		File loadFiles = f.listFiles();
		for(int i=0;i<loadFiles.length;i++) {
			File tempF = loadFiles*;
			if(tempF.isDirectory()) {
				continue;
			}
			if(tempF.isFile()) {
				tempF.delete();
			}
			
		}
	}