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

📄 ftpclient.java

📁 这是《Java案例精粹150例(上册)》一书配套的源代码。
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
			}
			dataSocket = portSocket.accept();
			portSocket.close();
		}
		return dataSocket; 
	}

    /** 打开一个到 <i>host </i>的FTP连接 */
    public void openServer(String host) throws IOException, 
	                                           UnknownHostException {
        int port = FTP_PORT;
        if (serverSocket != null)
            closeServer(); 
        serverSocket = new Socket(host, FTP_PORT);    
        serverOutput = new PrintWriter(new BufferedOutputStream(serverSocket.getOutputStream()),true);
        serverInput = new BufferedInputStream(serverSocket.getInputStream());
    }

    /** 打开到 host <i>host </i> 端口为 <i>port </i>的FTP连接 */
    public void openServer(String host, int port) throws IOException, UnknownHostException {
        if (serverSocket != null)
            closeServer();
        serverSocket = new Socket(host, port);
        serverOutput = new PrintWriter(new BufferedOutputStream(serverSocket.getOutputStream()),
                                       true);
        serverInput = new BufferedInputStream(serverSocket.getInputStream());

        if (readReply() == FTP_ERROR)
            throw new FtpConnectException("Welcome message");
    }
 
     /** 使用用户名 <i>user</i> 和密码 <i>password</i> 登录*/
    public void login(String user, String password) throws IOException {
        if (!serverIsOpen())
            throw new FtpLoginException("Error: not connected to host.\n");
        this.user = user;
        this.password = password;
        if (issueCommand("USER " + user) == FTP_ERROR)
            throw new FtpLoginException("Error: User not found.\n");
        if (password != null && issueCommand("PASS " + password) == FTP_ERROR)
            throw new FtpLoginException("Error: Wrong Password.\n");       
    }

    /** 只用用户名 <i>user</i> 不用密码登录 */
    public void login(String user) throws IOException {

        if (!serverIsOpen())
            throw new FtpLoginException("not connected to host");
        this.user = user;        
        if (issueCommand("USER " + user) == FTP_ERROR)
            throw new FtpLoginException("Error: Invalid Username.\n");                 
    }

    /** 以Ascii 模式从FTP server获取一个文件 */
    public BufferedReader getAscii(String filename) throws IOException {     
        Socket  s = null;
        try {
            s = openDataConnection("RETR " + filename);
        } catch (FileNotFoundException fileException) {fileException.printStackTrace();}
        return new BufferedReader( new InputStreamReader(s.getInputStream()));          
    }

    /** 以Binary 模式从FTP server获取一个文件 */
    public BufferedInputStream getBinary(String filename) throws IOException {     
        Socket  s = null;
        try {
            s = openDataConnection("RETR " + filename);
        } catch (FileNotFoundException fileException) {fileException.printStackTrace();}
        return new BufferedInputStream(s.getInputStream());          
    }


    /** 以Ascii 模式发送一个文件 */
    public BufferedWriter putAscii(String filename) throws IOException {
        Socket s = openDataConnection("STOR " + filename);
        return new BufferedWriter(new OutputStreamWriter(s.getOutputStream()),4096);
    }
     
    /** 以Binary 模式向server发送一个文件 */
    public BufferedOutputStream putBinary(String filename) throws IOException {
        Socket s = openDataConnection("STOR " + filename);
        return new BufferedOutputStream(s.getOutputStream());
    }

    /** 以Ascii 模式在server上创建或添加一个文件 */
    public BufferedWriter appendAscii(String filename) throws IOException {
        Socket s = openDataConnection("APPE " + filename);
        return new BufferedWriter(new OutputStreamWriter(s.getOutputStream()),4096);
    }

    /** 以Binary 模式在server上创建或添加一个文件 */
    public BufferedOutputStream appendBinary(String filename) throws IOException {
        Socket s = openDataConnection("APPE " + filename);
        return new BufferedOutputStream(s.getOutputStream());
    }

   /** NLIST 文件在远端 FTP server */
    public BufferedReader nlist() throws IOException {
        Socket s = openDataConnection("NLST");        
        return new BufferedReader( new InputStreamReader(s.getInputStream()));
    }

    /** LIST files 在远端 FTP server */
    public BufferedReader list() throws IOException {
        Socket s = openDataConnection("LIST");        
        return new BufferedReader( new InputStreamReader(s.getInputStream()));
    }

    /** 在FTP server上改变文件路径 */
    public void cd(String remoteDirectory) throws IOException {
        issueCommandCheck("CWD " + remoteDirectory);
    }

    /** 在server上改变文件名 */
    public void rename(String oldFile, String newFile) throws IOException {
         issueCommandCheck("RNFR " + oldFile);
         issueCommandCheck("RNTO " + newFile);
    }
      
    /** Site 命令 */ 
    public void site(String params) throws IOException {
         issueCommandCheck("SITE "+ params);
    }            
	
    /** 设置为'I'传输模式 */
    public void binary() throws IOException {
        issueCommandCheck("TYPE I");
        binaryMode = true;
    }

    /** 设置为'A'传输模式 */
    public void ascii() throws IOException {
        issueCommandCheck("TYPE A");
        binaryMode = false;
    }

    /** 发送Abort 命令 */
    public void abort() throws IOException {
        issueCommandCheck("ABOR");
    }

    /** 在远端系统浏览上一级目录 */
    public void cdup() throws IOException {
        issueCommandCheck("CDUP");
    }

    /** 在远端系统中创建一个目录 */
    public void mkdir(String s) throws IOException {
        issueCommandCheck("MKD " + s);
    }

    /** 在远端系统中删除某个路径 */
    public void rmdir(String s) throws IOException {
        issueCommandCheck("RMD " + s);
    }

    /** 删除文件 */
    public void delete(String s) throws IOException {
        issueCommandCheck("DELE " + s);
    }

    /** 获取当前目录名 */
    public void pwd() throws IOException {
        issueCommandCheck("PWD");
    }
    
    /** 获取远端系统的信息 */
    public void syst() throws IOException {
        issueCommandCheck("SYST");
    }


    /** 新的FTP客户端连接到host <i>host</i>. */
    public FtpClient(String host) throws IOException {      
        openServer(host, FTP_PORT);      
    }

    /** 新的FTP客户端连接到host <i>host</i>, port <i>port</i>. */
    public FtpClient(String host, int port) throws IOException {
        openServer(host, port);
    }
    
    /** 演示 */
    public static void main (String args []) throws IOException{
      System.out.println("Demo of FtpClient class.\n");
      // 标准登陆过程 
      FtpClient f = new FtpClient("ftp.zsu.edu.cn");
      System.out.print(f.getResponseString());
      f.login("anonymous");
      System.out.print(f.getResponseString());                       
      f.pwd(); 
      System.out.println(f.command);                  
      System.out.print(f.getResponseString());
      f.setPassive(true);
      
      // 使用列表
      System.out.println("\nDemo of nlist() function");
      f.ascii();  // 把客户端设为ASCII模式以获取文本列表   
      System.out.println(f.command);              
      System.out.print(f.getResponseString());     
      BufferedReader t = f.nlist();     // f.list提供了更多的一些细节信息
      System.out.println(f.command);
      System.out.print(f.getResponseString());  
      while( true ) {
         String stringBuffer = t.readLine();
         if( stringBuffer == null ) break;
         else System.out.println(stringBuffer);               
      }
      t.close();
      System.out.print(f.getResponseString());  
      // 下面使用 getAscii() 函数获取文件.  函数 getBinary() 也类似 
      System.out.println("\nDemo of getAscii() function");
      f.ascii();       //  设置传输模式为ASCII
      System.out.println(f.command);
      System.out.print(f.getResponseString());  
      BufferedReader bufGet = f.getAscii("welcome.msg");
      System.out.println(f.command);      
      System.out.print(f.getResponseString());      
      PrintWriter pOut = new PrintWriter(new BufferedWriter(new FileWriter("welcome.msg")));
      int i;                                
      char c[] = new char[4096];
      while ((i = bufGet.read(c)) != -1) 
        pOut.write(c,0,i);                                                   
      bufGet.close();
      pOut.close();            
      System.out.print(f.getResponseString());         
      // 下面使用appendAscii()函数添加一个文件,appendBinary()函数的使用类似
      System.out.println("\nDemo of appendAscii() function");
      BufferedWriter bufAppe;
      String localFile = "file name goes here"; 
      f.ascii();
      System.out.println(f.command);
      try {
      bufAppe = f.appendAscii(localFile);
      System.out.println(f.command);
      System.out.print(f.getResponseString());          
	  FileReader fIn = new FileReader(localFile);            
      BufferedReader bufIn = new BufferedReader(fIn);
      int k;
      char b[] = new char[1024];
      while ((k = bufIn.read(b)) != -1) 
        bufAppe.write(b,0,k);                                  
      bufIn.close();
      bufAppe.flush();
      bufAppe.close();                 
      }catch(Exception appendErr) {
         System.out.println(appendErr.toString());//printStackTrace();
         
      }
      System.out.print(f.getResponseString()); 
      // 下面使用putBianary()函数发送一个二进制文件,函数putAscii()类似
      System.out.println("\nDemo of putBinary() function");
      String localFile2 = "file name goes here"; 
      f.binary();
      System.out.println(f.command);
      BufferedOutputStream bufPut = f.putBinary(localFile2);
      System.out.println(f.command);
      System.out.print(f.getResponseString());     
      BufferedInputStream bufIn = new BufferedInputStream(new FileInputStream(localFile2));
      int j;
      byte b[] = new byte[1024];
      while ((j = bufIn.read(b)) != -1) 
        bufPut.write(b,0,j);                                  
      bufIn.close();
      bufPut.flush();
      bufPut.close();                 
      System.out.print(f.getResponseString()); 
      // 关闭连接
      f.closeServer();
      System.out.println(f.command);
      System.out.print(f.getResponseString());
    }
}

class FtpLoginException extends FtpProtocolException {
    FtpLoginException(String s) {
        super(s);
    }
}
class FtpConnectException extends FtpProtocolException {
    FtpConnectException(String s) {
        super(s);
    }
}

class FtpProtocolException extends IOException {
    FtpProtocolException(String s) {
        super(s);     
    }
}

⌨️ 快捷键说明

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