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

📄 ftpclient.java

📁 java应用开发详解
💻 JAVA
字号:
import java.net.*;import java.io.*;import java.util.Vector;import java.util.StringTokenizer;public class FtpClient {	private final String NEWLINE="\r\n";		private Socket s = null;	private BufferedReader sin = null;	private PrintWriter sout = null;	private boolean debug=false;	private Vector response = null;	private String type="ASCII";	private String getType() {		return type;	}	private void setType(String t) {		type=t;	}			public FtpClient (String host) {		  makeConnection(host);	}		private void makeConnection(String host) {		try {			s = new Socket (host, 21);			sin = new BufferedReader (new InputStreamReader (s.getInputStream()));			response = new Vector();			sout = new PrintWriter (s.getOutputStream());			response = new Vector();			getResponse();		}		catch (Exception e) {		}	}		private void getResponse () throws IOException {		String line;		line = sin.readLine();		while (line.length() ==0) {			line = sin.readLine();		}		response.addElement(line);	}		public String[] getResponseStream () {		try {			response.trimToSize();			String[] arrayResp= new String[response.size()];			response.copyInto(arrayResp);			response.removeAllElements();			return arrayResp;		}		catch (Exception e) {			String[] arrayResp={""};			return arrayResp;		}	}		private boolean sendCommand(String cmd) throws IOException {		sout.print (cmd + NEWLINE);		sout.flush();		try {			getResponse();		} catch (IOException e) {			response.addElement("Error. Ftp server is not responding.");			return handleError(cmd);		}		return false;	}		private String getCommand(String command) {		StringTokenizer st = new StringTokenizer(command);		String cmd =st.nextToken().toUpperCase();		return cmd;	}	private String getArgument(String command) {		StringTokenizer st = new StringTokenizer(command);		String arg =""; 		while (st.hasMoreTokens()) {			arg=st.nextToken();		}		return arg;	}		public boolean executeCommand (String command) throws IOException 	{		String cmd=getCommand(command);		String arg=getArgument(command);		if (cmd.equals("USER")) 		{			if (arg.toUpperCase().equals(cmd)) 			{				response.addElement("Incorrect command: USER username"+NEWLINE);				return false;			}			if (debug) response.addElement("--> USER " +arg);			return sendCommand("USER " + arg);		}		if (cmd.equals("PASS")) 		{			if (arg.toUpperCase().equals(cmd)) 			{				response.addElement("Incorrect command: PASS password"+NEWLINE);				return false;			}			if (debug) response.addElement("--> PASS ******");			return sendCommand("PASS " + arg);		}		if (cmd.equals("CD")) 		{			if (arg.toUpperCase().equals(cmd)) 			{				response.addElement("Incorrect command: CD directory"+NEWLINE);				return false;			}			if (debug) response.addElement("--> CWD " +arg);			return sendCommand("CWD " + arg);		}		if (cmd.equals("TYPE")) 		{			if (arg.toUpperCase().equals(cmd)) 			{			response.addElement("Type is set to "+getType()+"."+NEWLINE);				return false;			}			if (debug) response.addElement("--> TYPE " +arg);			return type(arg);		}		if (cmd.equals("GET")) 		{			if (arg.toUpperCase().equals(cmd)) 			{				response.addElement("Incorrect command: GET file"+NEWLINE);				return false;			}			if (debug) response.addElement("--> RETR " +arg);			return get(arg);		}		if (cmd.equals("PUT")) 		{			if (arg.toUpperCase().equals(cmd)) 			{				response.addElement("Incorrect command: PUT file"+NEWLINE);				return false;			}			if (debug) response.addElement("--> STOR " +arg);			return put(arg);		}		if (cmd.equals("LIST")||cmd.equals("LS")||cmd.equals("DIR")) 		{			if (debug) response.addElement("--> LIST");			return list();		}		if (cmd.equals("PWD")) 		{			if (debug) response.addElement("--> PWD");			return sendCommand("PWD");		}		if (cmd.equals("SYST")) 		{			if (debug) response.addElement("--> SYST");			return sendCommand("SYST");		}		if (cmd.equals("RNFR")) 		{			if (arg.toUpperCase().equals(cmd)) 			{				response.addElement("Incorrect command: RNFR old_filename"+NEWLINE);				return false;			}			if (debug) response.addElement("--> RNFR "+arg);			return sendCommand ("RNFR " + arg);		}		if (cmd.equals("RNTO")) 		{			if (arg.toUpperCase().equals(cmd)) 			{				response.addElement("Incorrect command: RNTO new_filename"+NEWLINE);				return false;			}			if (debug) response.addElement("--> RNTO "+arg);			return sendCommand ("RNTO " + arg);		}		if (cmd.equals("DELETE")) 		{			if (arg.toUpperCase().equals(cmd)) 			{				response.addElement("Incorrect command: DELETE file"+NEWLINE);				return false;			}			if (debug) response.addElement("--> DELE "+arg);			return sendCommand ("DELE " + arg);		}		if (cmd.equals("RMDIR")) 		{			if (arg.toUpperCase().equals(cmd)) 			{				response.addElement("Incorrect command: RMDIR dir"+NEWLINE);				return false;			}			if (debug) response.addElement("--> RMD "+arg);			return sendCommand ("RMD " + arg);		}		if (cmd.equals("MKDIR")) 		{			if (arg.toUpperCase().equals(cmd)) 			{				response.addElement("Incorrect command: MKDIR dir"+NEWLINE);				return false;			}			if (debug) response.addElement("--> MKD "+arg);			return sendCommand ("MKD " + arg);		}		if (cmd.equals("QUIT")) 		{			sendCommand("QUIT");			s.close();			return true;		}		if (cmd.equals("DEBUG")) 		{			if (debug) 			{ 				response.addElement("DEBUG mode OFF");			} else 			{				response.addElement("DEBUG mode ON");			}			debug=!debug;			return false;		}		if (cmd.equals("STATUS")) 		{			String status="\t";			status+="Type: "+getType()+";";			if (debug) status+=" DEBUG: ON;"; else status+=" DEBUG OFF;";			response.addElement(status+NEWLINE);			return false;		}		if (cmd.equals("HELP")||cmd.equals("?")) 		{			response.addElement(NEWLINE+"Commands:"+NEWLINE);			response.addElement("\tCD\t\tDEBUG\t\tDELETE\t\tDIR\t\tGET");			response.addElement("\tHELP\t\tLIST\t\tLS\t\tMKDIR\t\tPASS");			response.addElement("\tPUT\t\tPWD\t\tQUIT\t\tRMDIR\t\tRNFR");			response.addElement("\tRNTO\t\tSTATUS\t\tSYST\t\tTYPE\t\tUSER"+NEWLINE);			return false;		}		response.addElement("Invalid command"+NEWLINE);		return false;	}    	public boolean get (String input) 	{		Socket ftpData = null;		try {			ftpData = createDataSocket();			InputStream is = ftpData.getInputStream();			DataInputStream dis = new DataInputStream(is);			FileOutputStream fos = new FileOutputStream(input);			int c;			sendCommand ("RETR " + input);						if (getType().toUpperCase().compareTo("ASCII")==0) {				while ((c = dis.read()) != -1) {					fos.write(c);					fos.flush();				}			} else if (getType().toUpperCase().compareTo("IMAGE")==0) {				int size = 32768;				for (;;) {					byte[] buf = new byte[size];					int r = dis.read(buf);					if (r == -1) break;					fos.write(buf, 0, r);					fos.flush();				} 			}			getResponse();						ftpData.close();			fos.close();			return false;		}		catch (Exception e) {			return true;		}               	}	public boolean put (String input) {		Socket ftpData = null;		try {			ftpData = createDataSocket();			OutputStream os = ftpData.getOutputStream();			DataOutputStream dos = new DataOutputStream(os);			FileInputStream file = new FileInputStream(input);			sendCommand ("STOR " + input);									int c;			if (getType().toUpperCase().compareTo("ASCII")==0) {				String line="";				while ((c = file.read()) != -1) {					dos.write(c);					dos.flush();				}			} else if (getType().toUpperCase().compareTo("IMAGE")==0) {				int size = file.available();				byte[] buf = new byte[size];				for (int off = 0; off < size;) {					int r = file.read(buf, off, buf.length - off);                                   					if (r == -1) break;                                     					dos.write(buf, off, buf.length - off);                                  					dos.flush();                                    					off += r;                               					}                       				}                       				dos.close();                    				file.close();                    				ftpData.close();				getResponse();                  				return false;		}		catch (Exception e) {			System.err.println(e);			return true;		}	}	public boolean type (String input) throws IOException {		if (input.toUpperCase().compareTo("A")==0) {			setType("ASCII");			return sendCommand ("TYPE A");		} else {			if (input.toUpperCase().compareTo("I")==0) {				setType("IMAGE");				return sendCommand ("TYPE I");			}		}		return true;	}	public boolean list () throws IOException {		if (type("A")) return true;		Socket ftpData = null;		ftpData = createDataSocket();		InputStream is = ftpData.getInputStream();		BufferedReader ris = new BufferedReader (new InputStreamReader (is));				boolean result = sendCommand ("LIST");				String line = "";		int i;				while ((i = ris.read()) != -1) {			char c=(char) i;			if (c!='\n' && c!='\r') {				line+=c;			} else {				response.addElement(line);				line="";			}		}		getResponse();		is.close();		ftpData.close();		return result;	}		private Socket createDataSocket () throws IOException {		Socket dataSocket = null;				sout.print ("PASV"+NEWLINE);		sout.flush();		String res = sin.readLine();		response.addElement(res);				String[] parts = new String[6];		for (int i=0; i < parts.length; i++) {			parts[i] = "";		}				int pos = 0;		for (int i=4; i < res.length(); i++) {			if (Character.isDigit(res.charAt(i))) {				parts[pos] = parts[pos] + res.charAt(i);			} else if (res.charAt(i) == ',') {				pos++;			}		}		String ip = parts[0] + "." + parts[1] + "." + parts[2] + "." + parts[3];		int port = -1;		try { 		int big = Integer.parseInt(parts[4]) << 8;		    int small = Integer.parseInt(parts[5]);	      port = big + small;		}		catch(NumberFormatException e) {			e.printStackTrace();		}		dataSocket = new Socket (ip, port);				return dataSocket;	}	private boolean handleError(String cmd) throws IOException {		if (!getCommand(cmd).toUpperCase().equals("QUIT")) {			System.err.println("ftp> QUIT"+NEWLINE);		} else {			System.err.println(NEWLINE);		}		s.close();		return true;	}}	

⌨️ 快捷键说明

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