ftpconnection.java

来自「java ftp 操作代码,程序可以直接运行」· Java 代码 · 共 2,382 行 · 第 1/5 页

JAVA
2,382
字号
        //-------------------------------        return new String[0];    }    /** get a filename */    private String giveFile(StringTokenizer to, int lev)    {        String t2 = null;        for(int i = 0; i < lev; i++)        {            if(to.hasMoreTokens())            {                String t = to.nextToken();                //Log.out("> "+t);                if(t.equals(" ") || t.equals("\t"))                {                    // -                    /*                       while(to.hasMoreTokens())                       {                               t2 = to.nextToken();                           if(!t.equals(" ") && !t.equals("\t")) break;                       }                    */                    i--;                }            }        }        String tmp = "<error>";        /*        if(t2 != null)        {                tmp = t2;        }        */        while(tmp.equals(" ") || tmp.equals("\t") || tmp.equals("<error>"))        {            if(to.hasMoreTokens())            {                tmp = to.nextToken();            }            else            {                break;            }        }        while(to.hasMoreTokens())        {            tmp = tmp + to.nextToken();        }        //Log.out(">>> "+tmp);        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.    * (Used internally to check how to parse the ls-output)    *    * @return A Part of the SYST comman server response    */    public String getOsType()    {        if(TESTMODE)        {            return "MVS";        }        else        {            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++;        }        System.out.println("\n\n\n"+str);                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;    }    /** Download a file or directory.    * Uses multithreading if enabled and does not block.    *    * @param file The file to download    * @return An int-statuscode, see constants defined in this class for details    */    public int handleDownload(String file)    {        if(Settings.getEnableMultiThreading())        {            Log.out("spawning new thread for this download.");            FtpTransfer t = new FtpTransfer(host, port, getLocalPath(),                                            getCachedPWD(), file, username,                                            password, Transfer.DOWNLOAD,                                            handler, listeners, crlf);            lastTransfer = t;            return NEW_TRANSFER_SPAWNED;        }        else        {            Log.out("multithreading is completely disabled.");            return download(file);        }    }    /**    * Download a file or directory, block until finished.    *    * @param file The file to download    * @return An int returncode    */    public int download(String file)    {        //Log.out("ftp download started:" + this);        int stat;        if(file.endsWith("/"))        {            shortProgress = true;            fileCount = 0;            baseFile = file;            dataType = DataConnection.GETDIR;            stat = downloadDir(file);            //pause(100);            fireActionFinished(this);            fireProgressUpdate(baseFile,                               DataConnection.DFINISHED + ":" + fileCount, -1);            shortProgress = false;        }        else        {            dataType = DataConnection.GET;            stat = rawDownload(file);	    if(Settings.enableFtpDelays) {             try             {                Thread.sleep(100);             } catch(Exception ex) {}	    }            fireActionFinished(this);        }	if(Settings.enableFtpDelays) {         try         {            Thread.sleep(400);         }         catch(Exception ex)         {         }	}        return stat;    }    /**    * Get download InputStream.    *    * @param file The file to download    * @return An InputStream    */    public InputStream getDownloadInputStream(String file)    {        Log.out("ftp stream download started:" + this);        file = parse(file);        try        {            int p = 0;            dataType = DataConnection.GET;            file = StringUtils.getFile(file);            String path = getLocalPath() + file;            BufferedReader in = jcon.getReader();            modeStream();            p = negotiatePort();            dcon = new DataConnection(this, p, host, path, dataType, false, true);            while(!dcon.isThere())            {                pause(10);            }            jcon.send(RETR + " " + file);            return dcon.getInputStream();        }        catch(Exception ex)        {            ex.printStackTrace();            Log.debug(ex.toString() +                      " @FtpConnection::getDownloadInputStream");            return null;        }    }    private int 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(10);            }            jcon.send(RETR + " " + file);            String line = getLine(POSITIVE);            Log.debug(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 PERMISSION_DENIED;            }            else if(!line.startsWith(POSITIVE) && !line.startsWith(PROCEED))            {                return TRANSFER_FAILED;            }            // we need to block since some ftp-servers do not want the            // refresh command that dirpanel sends otherwise            while(!dcon.finished)            {                pause(10);            }        }        catch(Exception ex)        {            ex.printStackTrace();            Log.debug(ex.toString() + " @FtpConnection::download");            return TRANSFER_FAILED;        }        return TRANSFER_SUCCESSFUL;    }    private int 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 CHDIR_FAILED;        }        try        {            list();        }        catch(IOException ex)        {            return PERMISSION_DENIED;        }        String[] tmp = sortLs();        setLocalPath(path);        for(int i = 0; i < tmp.length; i++)        {            if(tmp[i].endsWith("/"))            {

⌨️ 快捷键说明

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