用commons-net和commons-io包实现ftp连接和上传

[ccn lang="java" tab_size="4" theme="blackboard" width="550" ]
package com.ergal.ftp;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

/**
* 测试ftp连接的
*
* @author Administrator
*
*/
public class TestLogin {
private FTPClient ftpClient = new FTPClient();

private OutputStream outSteam = null;

/**
* ftp服务器地址
*/
private String hostName = "192.168.1.12";

/**
* 登录名
*/
private String userName = "ftp";

/**
* 登录密码
*/
private String password = "ftp_1q2w3e4r";

/**
* 需要访问的远程目录
*/
private String remoteDir = "/pub";

/**
* 登录方法
*
*/
private void login() {
try {
// 链接到ftp服务器
ftpClient.connect(hostName, 2183);
System.out.println("连接到ftp服务器:" + hostName + " 成功..开始登录");
// 登录.用户名 密码
ftpClient.login(userName, password);
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
System.out.println("登录成功.");

FTPFile[] remoteFiles = ftpClient.listFiles(remoteDir);
System.out.println("目录" + remoteDir + "下的文件:");
if (remoteFiles != null) {
for (int i = 0; i < remoteFiles.length; i++) { String name = remoteFiles[i].getName(); long length = remoteFiles[i].getSize(); String readableLength = FileUtils .byteCountToDisplaySize(length); System.out.println(name + ":\t\t" + readableLength); } } //切换工作目录 ftpClient.changeWorkingDirectory("/pub"); // 添加一个文件 InputStream input; input = new FileInputStream("f:\\ohergal\\MyDocs\\OhergalScheme.txt"); BufferedInputStream buffered = new BufferedInputStream(input); boolean result = ftpClient.storeFile("OhergalScheme.txt", new BufferedInputStream(input)); buffered.close(); } catch (Exception e) { e.printStackTrace(); } finally { // 使用IO包关闭流 IOUtils.closeQuietly(outSteam); try { ftpClient.logout(); ftpClient.disconnect(); } catch (IOException ioe) { ioe.printStackTrace(); } } } public static void main(String[] args) { TestLogin listFtpfiles = new TestLogin(); listFtpfiles.login(); } } [/ccn]