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

📄 ftpconnection.java

📁 JAVA FTP客户端经典
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
        while(true)        {	    try            {                    tmp = in.readLine();                    if(tmp == null)                    {                        break;                    }                    Log.debug(tmp);                    if((tmp.startsWith(NEGATIVE) || (tmp.startsWith(NEGATIVE2))) &&		       (tmp.charAt(3) != MORE_LINES_APPENDED))                    {                        return tmp;                    }                    else		    {                        for(int i=0; i<until.length; i++)                        {                            if (tmp.startsWith(until[i]))                            {                                if (firstMatch == null)                                    firstMatch = tmp;                                if (tmp.charAt(3) != MORE_LINES_APPENDED)                                    return firstMatch;                            }                        }                    }            }            catch(Exception ex)            {                Log.debug(ex.toString() + " @FtpConnection::getLine");                break;            }        }		return null;    }    public boolean isConnected()    {    	return connected;    }    /** gets current remote directory */    public String getPWD()    {        if(connected) updatePWD();    	return pwd;    }    /** gets current remote directory (cached) */    public String getCachedPWD()    {    	return pwd;    }    /** updates PWD */    private void updatePWD()    {    	jcon.send(PWD);        String tmp = getLine(FTP257_PATH_CREATED);        String x1 = tmp.substring(tmp.indexOf("\"")+1);        x1 = x1.substring(0,x1.indexOf("\""));        if(!x1.endsWith("/"))        {        	x1 = x1 + "/";        }	pwd = x1;    }    /** change directory, use chdir instead    	if you do not parse the dir correctly...    */    public boolean chdirRaw(String dirName) {        jcon.send(CWD + " " + dirName);	return success(FTP250_COMPLETED);    }    private boolean success(String op)    {    	if(getLine(op).startsWith(op)) return true;	else return false;    }    /**     * Change to the parent of the current working directory.     * The CDUP command is a special case of CWD, and is included     * to simplify the implementation of programs for transferring     * directory trees between operating systems having different     * syntaxes for naming the parent directory.     */    public boolean cdup() {        jcon.send(CDUP);        return success(FTP200_OK);    }    /** create a directory */    public boolean mkdir(String dirName) {        jcon.send(MKD + " " + dirName);	return success(FTP257_PATH_CREATED);    }    private int negotiatePort() throws IOException    {    	String tmp = "";        if (Settings.getFtpPasvMode())        {            jcon.send(PASV);            tmp = getLine(FTP227_ENTERING_PASSIVE_MODE);	    if(!tmp.startsWith(NEGATIVE)) return getPasvPort(tmp);        }        tmp = getActivePortCmd();        jcon.send(tmp);        getLine(FTP200_OK);        return getActivePort();    }    /** lists remote directory */    public void list(String outfile) throws IOException    {    	String oldType = "";        try        {            BufferedReader in = jcon.getReader();            int p = 0;            modeStream();            oldType = getTypeNow();	    ascii();            p = negotiatePort();            dcon = new DataConnection(this,p,host,outfile,DataConnection.GET); //,null);//System.out.println("2...");	    while(!dcon.isThere()) pause(10);            jcon.send(LIST);//System.out.println("3...");            while(!dcon.finished) pause(10);            getLine(FTP226_CLOSING_DATA_REQUEST_SUCCESSFUL);//System.out.println("4...");	    if(!oldType.equals(ASCII)) type(oldType);     }     catch(Exception ex)     {        Log.debug("Cannot list remote directory!");	if(!oldType.equals(ASCII)) type(oldType);     	ex.printStackTrace();	throw new IOException(ex.getMessage());     }    }    /** parses directory and does a chdir() */    public boolean chdir(String p)    {     boolean tmp = chdirWork(p);     if(!tmp) return false;     else     {     	fireDirectoryUpdate(this);	return true;     }    }    /** parses directory and does a chdir(), but does not send an update signal */    public boolean chdirNoRefresh(String p)    {    	return chdirWork(p);    }    private boolean chdirWork(String p)    {        if(Settings.safeMode)        {	    noop();        }	p = parseSymlinkBack(p);        try        {	    // check if we don't have a relative path            if(!p.startsWith("/") && !p.startsWith("~"))            {                p = pwd + p;            }	    // argh, we should document that!            if (p.endsWith(".."))            {                boolean home = p.startsWith("~");                StringTokenizer stok = new StringTokenizer(p,"/");                //System.out.println("path p :"+p +" Tokens: "+stok.countTokens());                if (stok.countTokens()>2)                {                    String pold1="";                    String pold2="";                    String pnew="";                    while (stok.hasMoreTokens())                    {                        pold1=pold2;                        pold2=pnew;                        pnew=pnew+"/"+stok.nextToken();                    }                    p=pold1;                }                else                {                    p="/";                }                if(home)                {                    p = p.substring(1);                }            }            //System.out.println("path: "+p);            if(!chdirRaw(p))            {                return false;            }        }        catch(Exception ex)        {            Log.debug("(remote) Can not get pathname! "+pwd+":"+p);            ex.printStackTrace();            return false;        }	//fireDirectoryUpdate(this);	updatePWD();	return true;    }    /** waits a specified amount of time (in milliseconds) */    public void pause(int time)    {        try        {            Thread.sleep(time);        }        catch(Exception ex)        {            ex.printStackTrace();        }    }    /** get the local cwd */    public String getLocalPath()    {    	return localPath;    }    /** set the path downloaded to */    public boolean setLocalPath(String newPath)    {    	localPath = newPath;        if(!localPath.endsWith("/"))        {            localPath = localPath + "/";        }	return true;    }    public int getPort()    {        return port;    }    private int getPortA()    {        return porta;    }    private int getPortB()    {        return portb;    }    private void incrementPort()    {        portb++;    }    private String getActivePortCmd() throws UnknownHostException, IOException    {        InetAddress ipaddr = jcon.getLocalAddress();        String ip = ipaddr.getHostAddress().replace('.', ',');        incrementPort();        int a = getPortA();        int b = getPortB();        String ret = "PORT " + ip + "," + a + "," + b;	//System.out.println(ret);	return ret;    }    /**     * Tell server we want binary data connections.     */    public void binary()    {   // possible responses 200, 500, 501, 504, 421 and 530        type(BINARY);    }    /**     * Tell server we want ascii data connections.     */    public void ascii()    {        type(ASCII);    }    public final static String ASCII = "A";    public final static String BINARY = "I";    public final static String EBCDIC = "E";    public final static String L8 = "L 8";    private String typeNow = "";    public boolean type(String code)    {        jcon.send(TYPE + " " + code);        if(getLine(FTP200_OK).startsWith(FTP200_OK))	{	 typeNow = code;	 return true;	 }	 return false;    }        public String getTypeNow()    {    	return typeNow;    }    /**     * do nothing, but flush buffers     */    public void noop()    {        jcon.send(NOOP);        getLine(FTP200_OK);    }         public void abort()    {        jcon.send(ABOR);        getLine(POSITIVE); // 226    }     /**     * This command is used to find out the type of operating     * system at the server. The reply shall have as its first     * word one of the system names listed in the current version     * of the Assigned Numbers document (RFC 943).     */    public String system()    {   // possible responses 215, 500, 501, 502, and 421        jcon.send(SYST);        String response = getLine(FTP215_SYSTEM_TYPE);        if (response != null)        {            StringTokenizer st = new StringTokenizer(response);            if (st.countTokens() >= 2)            {                 st.nextToken();                 String os = st.nextToken();                 setOsType(os);            }        }        else        {            setOsType("UNIX");        }        return response;    }    public final static String STREAM = "S";    public final static String BLOCKED = "B";    public final static String COMPRESSED = "C";    private static boolean useStream = true;    private static boolean useBlocked = true;    private static boolean useCompressed = true;    public void modeStream()    {        if (useStream && !modeStreamSet) {	    String ret = mode(STREAM);            if (ret != null && ret.startsWith(NEGATIVE)) useStream = false;	    else modeStreamSet = true;        }    }    /**     * unsupported at this time     */    public void modeBlocked()    {        if (useBlocked) {            if (mode(BLOCKED).startsWith(NEGATIVE))                useBlocked = false;        }    }    /*     * unsupported at this time     */    public void modeCompressed()    {        if (useCompressed) {            if (mode(COMPRESSED).startsWith(NEGATIVE))                useCompressed = false;        }    }    public String mode(String code)    {        jcon.send(MODE + " " + code);	String ret = "";		try 	{ 		ret = getLine(FTP200_OK); 	}	catch(Exception ex) 	{		ex.printStackTrace();	}		return ret;    }    public String getHost()    {        return host;    }    public String getUsername()    {        return username;    }    public String getPassword()    {        return password;    }        public DataConnection getDataConnection()    {    	return dcon;    }    public void addConnectionListener(ConnectionListener l)    {    	listeners.add(l);    }    public void setConnectionListeners(Vector l)    {    	listeners = l;    }  /** remote directory has changed */    public void fireDirectoryUpdate(FtpConnection con)    {    	if(listeners == null) return;	else	{		for(int i=0; i<listeners.size(); i++)		{			((ConnectionListener)listeners.elementAt(i)).updateRemoteDirectory(con);		}	}    }    /** progress update */    public void fireProgressUpdate(String file, String type, int bytes)    {    	//System.out.println(listener);    	if(listeners == null) return;	else	{	 for(int i=0; i<listeners.size(); i++)	 {	   ConnectionListener listener = (ConnectionListener) listeners.elementAt(i);	   if(shortProgress && Settings.shortProgress)	  {		if(type.startsWith(DataConnection.DFINISHED))		{			 listener.updateProgress( baseFile, DataConnection.DFINISHED+":"+fileCount, bytes);		}		else if(isDirUpload) listener.updateProgress( baseFile, DataConnection.PUTDIR+":"+fileCount, bytes);		else listener.updateProgress( baseFile, DataConnection.GETDIR+":"+fileCount, bytes);	   }	   else listener.updateProgress(file, type, bytes);	  }	}    }    /** connection is there and user logged in */    public void fireConnectionInitialized(FtpConnection con)    {    	if(listeners == null) return;	else	{		for(int i=0; i<listeners.size(); i++)		{			((ConnectionListener)listeners.elementAt(i)).connectionInitialized(con);		}	}    }    /** we are not logged in for some reason */    public void fireConnectionFailed(FtpConnection con, String why)    {    	if(listeners == null) return;	else	{		for(int i=0; i<listeners.size(); i++)		{			((ConnectionListener)listeners.elementAt(i)).connectionFailed(con, why);		}	}    }    /** transfer is done */    public void fireActionFinished(FtpConnection con)    {    	if(listeners == null) return;	else	{		for(int i=0; i<listeners.size(); i++)		{			((ConnectionListener)listeners.elementAt(i)).actionFinished(con);		}	}    }    public ConnectionHandler getConnectionHandler()    {    	return handler;    }    public void setConnectionHandler(ConnectionHandler h)    {    	handler = h;    }}

⌨️ 快捷键说明

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