⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ftpclient.java

📁 一个实用工具类
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/* * Copyright (C) butor.com. All rights reserved. * * This software is published under the terms of the GNU Library General * Public License (GNU LGPL), a copy of which has been included with this * distribution in the LICENSE.txt file.  */package org.butor.net.ftp; import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.BufferedReader;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.DataOutputStream;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.ObjectInputStream;import java.io.OutputStream;import java.io.Serializable;import java.net.Socket;import java.util.StringTokenizer;import java.util.Vector;import org.butor.log.Log;import org.butor.net.INetworkEventListener;import org.butor.net.NetworkClient;/** * FTP client application/protocol * * @author Aiman Sawan */public class FtpClient extends NetworkClient implements Serializable {	protected String f_userName;	protected String f_account;	protected String f_password;	protected String f_initialDir;	    	protected boolean f_loggedIn;	protected char f_type;	protected int f_bytesTransferred;		public static final char ASCII_TRANSFER_MODE = 'A';	public static final char EBCDIC_TRANSFER_MODE = 'E';	public static final char BINARY_TRANSFER_MODE = 'I';public void changeDirectory(String dir) throws IOException {	checkLoggedIn();	checkStringOk(dir, "No remote path specified");	checkReply(sendCommand("CWD " + dir), "2");	return;}public void changeToParentDirectory() throws IOException {	checkLoggedIn();	checkReply(sendCommand("CDUP"), "2");	return;}protected void checkLoggedIn() throws IOException {	/*	 * Is connection alive?	 *//*	try {		String curDir = currentDirectory(false);	} catch (IOException e) {		logIn();	}*/		if (!isLoggedIn()) {		throw new IOException("Not logged on");	}}public void createDirectory(String dir) throws IOException {	checkLoggedIn();	checkStringOk(dir, "No remote path specified");	checkReply(sendCommand("MKD " + dir), "2");}public String currentDirectory() throws IOException {	checkLoggedIn();	String reply = sendCommand("PWD");	checkReply(reply, "257");		int i = reply.indexOf("\"");	int j = reply.lastIndexOf("\"");	return reply.substring(i + 1, j);}public void deleteDirectory(String dir) throws IOException {	checkLoggedIn();	checkStringOk(dir, "No remote path specified");	checkReply(sendCommand("RMD " + dir), "2");}public void deleteFile(String file) throws IOException {	checkLoggedIn();	checkStringOk(file, "No file information specified");	checkReply(sendCommand("DELE " + file), "2");}private String[] doDirList(String dir, boolean showFilesDetail) throws IOException {	checkLoggedIn();	checkReply(sendCommand("TYPE A"), "2");	Vector vector = new Vector();	Socket socket = enterPassiveMode();	trace(socket.toString());		try {		if(!isStringOk(dir)) {			if (showFilesDetail) {				checkReply(sendCommand("LIST"), "1");			} else {				checkReply(sendCommand("NLST"), "1");			}		} else {			if (showFilesDetail) {				checkReply(sendCommand("LIST " + dir), "1");			} else {				checkReply(sendCommand("NLST " + dir), "1");			}		}						InputStream inputstream = socket.getInputStream();		BufferedReader bufferedreader = null;		try {			bufferedreader = new BufferedReader(new InputStreamReader(inputstream));			String s1;			while((s1 = bufferedreader.readLine()) != null) {				trace(s1);				vector.addElement(s1);			}		} finally {			if(inputstream != null) {				inputstream.close();			}						if(bufferedreader != null) {				bufferedreader.close();			}			checkReply(getReply(), "2");		}	} finally {		socket.close();	}		if(vector.isEmpty()) {		return null;	} else {		String as[] = new String[vector.size()];		vector.copyInto(as);		return as;	}}protected Socket enterPassiveMode() throws IOException {	String reply;	checkReply(reply = sendCommand("PASV"), "2");	int i = reply.lastIndexOf(40);	int j = reply.lastIndexOf(41);		if(i == -1 && j == -1) {		i = reply.lastIndexOf(32);		j = reply.trim().length();	}		if(i != -1 && j <= i) {		Log.logStr(this, Log.LOG_TYPE_ERROR, "enterPassiveMode()", "i != -1 && j <= i");		throw new IOException("Bad PASV response from server");	}			String s1 = reply.substring(i + 1, j);	String as[] = new String[6];	StringTokenizer stringtokenizer = new StringTokenizer(s1, ",");	Log.logStr(Log.LOG_LEVEL_FULL, this, Log.LOG_TYPE_INFO, "enterPassiveMode", reply);	if(stringtokenizer.countTokens() != 6) {		Log.logStr(this, Log.LOG_TYPE_ERROR, "enterPassiveMode()", "stringtokenizer.countTokens() != 6");		throw new IOException("Bad PASV response from server");	}		int k = 0;	while(stringtokenizer.hasMoreElements()) {		as[k++] = (String)stringtokenizer.nextElement();	}		int l;	try {		int i1 = Integer.parseInt(as[4].trim());		int j1 = Integer.parseInt(as[5].trim());		l = i1 << 8 | j1;	} catch(NumberFormatException numberformatexception) {		numberformatexception.printStackTrace();		throw new IOException("Bad PASV response from server");	}		return new Socket(f_host, l);}public boolean existsDirectory(String dir) throws IOException {	checkLoggedIn();	checkStringOk(dir, "No remote path specified");	String curDir = null;		try {		curDir = currentDirectory();		changeDirectory(dir);		changeDirectory(curDir);	} catch (IOException e) {		if (curDir != null) {			changeDirectory(curDir);		}		return false;	}	return true;}private String extractFilename(String file) {	int i = file.lastIndexOf("/");		if (i == -1) {		return file;	} else {		return file.substring(i + 1);	}}public String getAccount() {	return f_account;}public int getBytesTransferred() {	return f_bytesTransferred;}public String getPassword() {	return f_password;}public int getPort() {	return f_port;}/** * Gets Socket of stored file.  * The file will be created on remote and a socket on it will be returned to * makes writes on its output stream. * * @param remoteFile String, name of remote file to create. */public Socket getSocketToStoreFile(String remoteFile) throws IOException {	checkLoggedIn();	checkStringOk(remoteFile, "Remote file name is missing!");	f_bytesTransferred = 0;	Socket socket = enterPassiveMode();	trace("Remote filename = " + remoteFile);	checkReply(sendCommand("STOR " + remoteFile), "1");		return socket;}public char getType() {	return f_type;}public String getUser() {	return f_userName;}public boolean isLoggedIn() {	return f_loggedIn;}public void logIn(String userName, String password, String account) 		throws IOException, java.net.ConnectException, java.net.UnknownHostException {	setUserName(userName);	setPassword(password);	setAccount(account);		checkStringOk(userName, "User name is missing!");	checkStringOk(password, "Password is missing!");		try {		checkReply(connect(), "2");				String reply = sendCommand("USER " + userName);		if (reply.startsWith("2") || reply.startsWith("3")) {			if (reply.startsWith("331")) {				reply = sendCommand("PASS " + password);				if (reply.startsWith("332")) {					checkReply(sendCommand("ACCT " + account), "2");				} else {					checkReply(reply, "2");				}			}		} else {			Log.logStr(this, Log.LOG_TYPE_ERROR, "logIn()", "");			throw new IOException(reply);		}						f_loggedIn = true;			} catch(IOException e) {		close();		throw e;	}		if (f_initialDir != null) {		// Disable session if initial dir could be set.		try {			changeDirectory(f_initialDir);		} catch (IOException e) {			Log.logStr(this, Log.LOG_TYPE_ERROR, "logIn", 					"Initial dir could not be set: " + f_initialDir + ".  FTP Session will disabled.");			close();		}	}		setType(f_type);		fireNetworkEvent(INetworkEventListener.EVENT_LOGGED_IN, null);}public void logIn(String userName, String password) throws IOException {	logIn(userName, password, "");}public void logIn() throws IOException {		logIn(f_userName, f_password, f_account);}public void logOut() throws IOException {//!AS	checkLoggedIn();		try {		checkReply(sendCommand("QUIT"), "2");		f_loggedIn = false;	} finally {		close();	}	fireNetworkEvent(INetworkEventListener.EVENT_LOGGED_OUT, null);}private void readObject(ObjectInputStream ois) 		throws IOException, ClassNotFoundException {	ois.defaultReadObject();}public void renameFile(String oldFileName, String newFileName) throws IOException {	checkLoggedIn();	checkReply(sendCommand("RNFR " + oldFileName), "3");	checkReply(sendCommand("RNTO " + newFileName), "2");}public void reset() throws IOException {	checkLoggedIn();	checkReply(sendCommand("REIN"), "2");	return;}public String[] retrieveDirectory()	throws IOException {	String as[] = null;	as = retrieveDirectory(currentDirectory());	return as;}public String[] retrieveDirectory(String s) throws IOException {	String as[] = null;	as = doDirList(s, true);	return as;}public void retrieveFile(String remoteFile, String localFile, char type) throws IOException {	checkLoggedIn();	checkStringOk(remoteFile, "No remote file information specified");	checkStringOk(localFile, "No local file information specified");	f_bytesTransferred = 0;	Socket socket = enterPassiveMode();	try {		checkReply(sendCommand("RETR " + remoteFile), "1");		trace("After creating a new socket");					trace("Local filename = " + localFile);		BufferedInputStream bufferedinputstream = new BufferedInputStream(socket.getInputStream());		BufferedOutputStream bufferedoutputstream = null;		try {			bufferedoutputstream = new BufferedOutputStream(new FileOutputStream(localFile));			transfer(bufferedinputstream, bufferedoutputstream, type);		} finally {			if (bufferedoutputstream != null) {				bufferedoutputstream.close();			}						if (bufferedinputstream != null) {				bufferedinputstream.close();			}						checkReply(getReply(), "2");		}	} finally {		socket.close();	}		socket.close();}public void retrieveFile(String remoteFile, String localFile) throws IOException {	retrieveFile(remoteFile, localFile, f_type);}public void retrieveFile(String file) throws IOException {	retrieveFile(file, file);}/********************** * Philip Whitford *  * */public void retrieveFileToConsumer(String path, String remoteFile, IFTPInputStreamConsumer inStreamConsumer) throws IOException {	retrieveFileToConsumer(path, remoteFile, BINARY_TRANSFER_MODE, inStreamConsumer);}/********************** * Philip Whitford *  * */public void retrieveFileToConsumer(String path, String remoteFile,  char transferType, IFTPInputStreamConsumer inStreamConsumer) throws IOException {			if (path == null || remoteFile == null || inStreamConsumer == null) {		Log.logStr(this, Log.LOG_TYPE_ERROR, "retreiveFileToConsumer()", "One or more parameter is null");		return;	}		checkLoggedIn();	changeDirectory(path);	checkStringOk(remoteFile, "No file information specified");	f_bytesTransferred = 0;	Socket socket = enterPassiveMode();	setType(transferType);				checkReply(sendCommand("RETR " + remoteFile), "1");		trace("After creating a new socket");	InputStream s = socket.getInputStream();		try {		try {			boolean continueToRead = true;			if (s != null) {				int data = 0;				while (data >= 0 && continueToRead) {					data = s.read();					continueToRead = inStreamConsumer.consume(data);				}			}		} finally {			if (s != null) {				s.close();			}			checkReply(getReply(), "2");

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -