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

📄 ftpconnection.java

📁 JAVA FTP客户端经典
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
            {                tmp = to.nextToken();            }            else                break;        }        while(to.hasMoreTokens())        {            tmp = tmp + to.nextToken();        }        return tmp;    }    /** get a filesize */    private String giveSize(StringTokenizer to, int lev)    {        for(int i=0; i<lev; i++)        {            if(to.hasMoreTokens())            {                if(to.nextToken().equals(" "))                {                    i--;                }            }        }        while(to.hasMoreTokens())        {            String tmp = to.nextToken();            if(!tmp.equals(" "))            {                try                {                    Integer.parseInt(tmp);                }                catch(NumberFormatException ex)                {                    return "-1";                }                return tmp;            }        }        return "-2";    }    /** try to determine the os-type to properly parse the ls-output */    public String getOsType()    {        return osType;    }    private void setOsType(String os)    {        osType = os.toUpperCase();    }        private int getPasvPort(String str)    {    	int start = str.lastIndexOf(",");	String lo = "";	start++;		while(start < str.length())	{		char c = str.charAt(start);		if(!Character.isDigit(c)) break;		lo = lo + c;		start++;	}		String hi = "";	start = str.lastIndexOf(",");	start --;		while(true)	{		char c = str.charAt(start);		if(!Character.isDigit(c)) break;		hi = c + hi;		start--;	}	//System.out.print(hi+":"+lo+" - ");	return (Integer.parseInt(hi) * 256 + Integer.parseInt(lo));    }    private int getActivePort()    {        return getPortA() * 256 + getPortB();    }    /** parse a symlink */    private  String parseSymlink(String file)    {        if(file.indexOf("->") >= 0)        {            //System.out.print(file+" :-> symlink converted to:");            file = file.substring(0, file.indexOf("->")).trim();	    file = file + "###";            //System.out.println(file);        }        return file;    }     /** parse a symlink and cut the back */    private String parseSymlinkBack(String file)    {        if(file.indexOf("->") >= 0)        {            //System.out.print(file+" :-> symlink converted to:");            file = file.substring(file.indexOf("->")+2).trim();            //System.out.println(file);        }        return file;    }        /** test for symlink */    private  boolean isSymlink(String file)    {        if(file.indexOf("->") >= 0)        {            return true;        }        return false;    }    public void handleDownload(String file)    {      if(Settings.getEnableMultiThreading())      {	        FtpTransfer t = new FtpTransfer(host, port, getLocalPath(), getCachedPWD(), file, username, password, Transfer.DOWNLOAD, handler, listeners);      }      else      {      	download(file);      }    }    /** download a file */    public void download(String file)    {      if(file.endsWith("/"))      {        shortProgress = true;	fileCount = 0;	baseFile = file;	dataType = DataConnection.GETDIR;      	downloadDir(file);	pause(500);	fireActionFinished(this);	fireProgressUpdate(baseFile,DataConnection.DFINISHED + ":" + fileCount, -1);	shortProgress = false;      }     else     {     	dataType = DataConnection.GET;      	rawDownload(file);	fireActionFinished(this);     }     	try{Thread.sleep(400);}	catch(Exception ex) {}    }    private void rawDownload(String file)    {        file = parse(file);        //String path = file;        try        {            int p =0;             //if(isRelative(file)) path = getLocalPath() + file;	     file = StringUtils.getFile(file);	     String path = getLocalPath() + file;	     //System.out.println(file + " : " + path);            BufferedReader in = jcon.getReader();            modeStream();            //binary();            p = negotiatePort();            File f = new File(path);	    //System.out.println("path: "+path);            boolean resume = false;            if(f.exists() && Settings.enableResuming)            {                jcon.send(REST + " " + f.length());                if(getLine(PROCEED) != null)                {                    resume = true;                }            }            dcon = new DataConnection(this,p,host,path,dataType, resume); //, new Updater());            while(!dcon.isThere()) pause(100);            jcon.send(RETR + " " + file);	    String line = in.readLine();            Log.debug(line);	    //System.out.println(line);	    // file has been created even if not downloaded, delete it	    if(line.startsWith(NEGATIVE))	    {	    	File f2 = new File(path);	        if(f2.exists() && f2.length() == 0) f2.delete();		return;	    }	    // we need to block since some ftp-servers do not want the	    // refreh command that dirpanel sends otherwise	    while(!dcon.finished) pause(100);        }        catch(Exception ex)        {	    ex.printStackTrace();            Log.debug(ex.toString()+" @FtpConnection::download");        }    }    /** recursive download of a directory */        public void downloadDir(String dir)    {        if(!dir.endsWith("/"))        {            dir = dir + "/";        }	if(StringUtils.isRelative(dir)) dir = getCachedPWD() + dir;	String path = getLocalPath() + StringUtils.getDir(dir);	//System.out.println("path: "+path);	String pwd = getCachedPWD()+StringUtils.getDir(dir);	String oldDir = getLocalPath();        String oldPwd = getCachedPWD();        File f = new File(path);        if(!f.exists())        {            if(!f.mkdir())            {                Log.debug("Can't create directory: "+dir);            }            else                Log.debug("Created directory...");        }	setLocalPath(path);        if(!chdirNoRefresh(pwd)) return;	try	{		list(Settings.ls_out);	}	catch(IOException ex)	 {		// probably we don't have permission to ls here		return;	}        String tmp[] = sortLs(Settings.ls_out);	setLocalPath(path);        for(int i=0; i<tmp.length; i++)        {            if(tmp[i].endsWith("/"))            {                if(tmp[i].trim().equals("../") || tmp[i].trim().equals("./"))                {                    Log.debug("Skipping " + tmp[i].trim());                }                else                {		    if(!work)		    {			return;		    }		    downloadDir(tmp[i]);                }            }            else            {                //System.out.println( "file: " + getLocalPath() + tmp[i] + "\n\n");		if(!work)		{			return;		}		fileCount++;                rawDownload(getLocalPath() + tmp[i]);            }        }	chdirNoRefresh(oldPwd);	setLocalPath(oldDir);    }    public void handleUpload(String file)    {      if(Settings.getEnableMultiThreading() && (!Settings.getNoUploadMultiThreading()))      {        	FtpTransfer t = new FtpTransfer(host, port, getLocalPath(), getCachedPWD(), file, username, password, Transfer.UPLOAD, handler, listeners);      }      else      {      	upload(file);      }    }    public void upload(String file)    {    	hasUploaded = true;     if(new File(file).isDirectory())     {        shortProgress = true;	fileCount = 0;	baseFile = file;	dataType = DataConnection.PUTDIR;	isDirUpload = true;     	uploadDir(file);	shortProgress = false;	//System.out.println(fileCount + ":" + baseFile);	fireProgressUpdate(baseFile,DataConnection.DFINISHED + ":" + fileCount, -1);	fireActionFinished(this);	fireDirectoryUpdate(this);     }     else     {     	dataType = DataConnection.PUT;	rawUpload(file);	fireActionFinished(this);	fireDirectoryUpdate(this);     }     	try{Thread.sleep(500);}	catch(Exception ex) {}    }    /** uploads a file */    private void rawUpload(String file)    {    	file = parse(file);        String path =file;        try        {            int p=0;            if(StringUtils.isRelative(file)) path = getLocalPath() + file;	    file = StringUtils.getFile(file);            BufferedReader in = jcon.getReader();            modeStream();            //binary();	    p = negotiatePort();	    //File f = new File(file);            dcon = new DataConnection(this,p,host,path,dataType); //, new Updater());            while(!dcon.isThere())                pause(100);	    //System.out.println(path + " : " + file);            Log.debug("File: "+file);            jcon.send(STOR + " " + file);            Log.debug(in.readLine());	    // we need to block since some ftp-servers do not want the	    // refresh command that dirpanel sends otherwise	    while(!dcon.finished) pause(100);        }        catch(Exception ex)        {	    ex.printStackTrace();            Log.debug(ex.toString()+" @FtpConnection::upload");        }    }    /** uploads a directory recursively */    public void uploadDir(String dir)    {        //System.out.println("up");        if(dir.endsWith("\\"))        {            System.out.println("Something's wrong with the selected directory - please report this bug!");        }        if(!dir.endsWith("/"))        {            dir = dir + "/";        }	if(StringUtils.isRelative(dir)) dir = getLocalPath() + dir;	String single = StringUtils.getDir(dir);	String path = dir.substring(0, dir.indexOf(single));        String remoteDir = getCachedPWD() + single;	//StringUtils.removeStart(dir,path);	String oldDir = getCachedPWD();        if(Settings.safeMode) noop();        boolean successful = mkdir(remoteDir);        if (!successful) return;        if(Settings.safeMode) noop();	chdirNoRefresh(remoteDir);        File f2 = new File(dir);        String tmp[] = f2.list();        for(int i=0; i<tmp.length; i++)        {	    String res = dir+tmp[i];            File f3 = new File(res);            if(f3.isDirectory())            {	    	if(!work)		{			return;		}                uploadDir(res);            }            else            {		//System.out.println(">>>\nlp: "+path+single + "\nrp: ");		//System.out.println(remoteDir +"\nres: "+res);		if(!work)		{			return;		}		fileCount++;                rawUpload(res);            }        }	chdirNoRefresh(oldDir);    }    private String parse(String file)    {	file = parseSymlink(file);	return file;    }    /** recursive delete remote directory */    private void cleanDir(String dir, String path)    {        if(!dir.endsWith("/"))        {            dir = dir + "/";        }        String remoteDir = StringUtils.removeStart(dir,path);        String oldDir = pwd;        chdirNoRefresh(pwd+remoteDir);	try {		list(Settings.ls_out);	} catch(IOException ex) {		// probably we don't have permission to ls here		return;	}	String tmp[] = sortLs(Settings.ls_out);        chdirNoRefresh(oldDir);        if(tmp == null)            return;        for(int i=0; i<tmp.length; i++)        {	 tmp[i] = parseSymlink(tmp[i]);	 if(tmp[i].equals("./") || tmp[i].equals("../"))	 {	 	//System.out.println(tmp[i]+"\n\n\n");	 	continue;	 }	 //System.out.println(tmp[i]);	 //pause(500);            if(tmp[i].endsWith("/"))            {                //   System.out.println(dir);                cleanDir(dir+tmp[i],path);                removeFileOrDir(dir+tmp[i]);            }            else            {                //   System.out.println(dir+tmp[i]);                removeFileOrDir(dir+tmp[i]);            }        }    }    /** remove a remote file or directory */    public void removeFileOrDir(String file) {    	file = parseSymlink(file);	if(file.endsWith("/"))	{		cleanDir(file, getCachedPWD());		jcon.send(RMD + " " + file);	}	else	jcon.send(DELE + " " + file);        getLine(FTP250_COMPLETED);    }    /** disconnect */    public void disconnect() { 	jcon.send(QUIT);	getLine(FTP221_SERVICE_CLOSING);	connected = false;    }    /** execute noop -> command -> noop */    public void sendRawCommand(String cmd)    {        noop();	Log.clearCache();        jcon.send(cmd);        noop();    }    /** reads until line found or error */    public String getLine(String until)    {        return getLine(new String[] { until });    }    /** reads until line found or error */    public String getLine(String until[])    {        BufferedReader in = null;        try        {            in = jcon.getReader();        }        catch(Exception ex)        {            Log.debug(ex.toString()+" @FtpConnection::getLine");        }        String firstMatch = null;        String tmp;

⌨️ 快捷键说明

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