Apache ftp client 上传进度跟踪

nile 发布于 2010/09/21 13:06
阅读 1K+
收藏 2

项目中用到ftp上传数据,用apache ftp client写了一个工具类。默认的ftpclient storefile是不能设置跟踪进度的。这里用了另外一个api,做了一个简单的包装。

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.SocketException;

import javax.swing.event.EventListenerList;

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

public class GFtpCleint {
	private EventListenerList eventListenerList = new EventListenerList();
	private FTPClient client;

	public GFtpCleint() {
		client = new FTPClient();
	}

	public void connect(String hostname, int port) throws SocketException, IOException {
		client.connect(hostname, port);
	}

	public boolean login(String username, String password) throws IOException {
		return client.login(username, password);
	}

	public boolean logout() throws IOException {
		return client.logout();
	}

	public int quit() throws IOException {
		return client.quit();
	}

	public void sendFile(String file, String to, boolean binary) throws IOException {
		if (binary)
			client.setFileType(FTPClient.BINARY_FILE_TYPE);
		File _file = new File(file);
		int n = -1;
		long size = _file.length();
		long trans = 0;
		int bufferSize = client.getBufferSize();
		byte[] buffer = new byte[bufferSize];

		FileInputStream fileInputStream = new FileInputStream(_file);
		OutputStream outputstream = client.storeFileStream(to);
		while ((n = fileInputStream.read(buffer)) != -1) {
			outputstream.write(buffer);
			trans += n;
			TransforEventListener[] listeners = eventListenerList.getListeners(TransforEventListener.class);
			for (int i = listeners.length -1; i >= 0  ; i--) {
				listeners[i].update(trans, size);
			}
		}
		fileInputStream.close();
		outputstream.flush();
		outputstream.close();
	}

	public void addListener(TransforEventListener l) {
		eventListenerList.add(TransforEventListener.class, l);
	}

	public void removeListener(TransforEventListener l) {
		eventListenerList.remove(TransforEventListener.class, l);
	}

}

 

import java.util.EventListener;

public interface TransforEventListener extends EventListener{
	void update(long send,long size ) ;
}

http://jsxnc.com/posts/nile/232

加载中
返回顶部
顶部