在java中使用FTP程序

时间:2013-07-23 05:35:59

标签: java sockets ftp jvm ftp-client

我一直在使用教程来列出来自FTP服务器from here的目录。但它提供了例外java.net.SocketException: Software caused connection abort: socket write error 该图片也附加enter image description here 我使用了ftp4j库和示例代码,但也有一些错误,任何人都可以说出原因,因为我看不出任何原因, 可能是我必须为JVM启用一些安全限制? (只是一个想法) 谢谢温柔

1 个答案:

答案 0 :(得分:0)

假设您尝试使用任何FTP客户端(例如FileZilla)连接到此FTP服务器,以下是基于Apache Commons FTP列出文件和目录的代码(定义SERVER_NAME,USER_NAME和PASSWORD)。

        FTPClient ftp = new FTPClient();
        DateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 

        FTPClientConfig config = new FTPClientConfig();
        //optional - set timezone of the server 
        config.setServerTimeZoneId("America/New_York");

        ftp.configure(config );

        try {

            int reply;

            ftp.connect(SERVER_NAME);
            ftp.login(USER_NAME, PASSWORD);
            System.out.println("Connected to " + SERVER_NAME + ".");
            System.out.println(ftp.getReplyString());

            //After connection attempt, check the reply code to verify success.
            reply = ftp.getReplyCode();

            if(!FTPReply.isPositiveCompletion(reply)) {
              ftp.disconnect();
              System.out.println("Failed to connect to FTP server");
              System.exit(1);
            }

             //use binary mode
             ftp.setFileType(FTP.BINARY_FILE_TYPE);
             //use passive mode for firewalls
             ftp.enterLocalPassiveMode();

             FTPListParseEngine engine = ftp.initiateListParsing(".");

             while (engine.hasNext()) {
                FTPFile[] files = engine.getNext(25);  
                for (FTPFile file : files) {
                    String details = file.getName();
                    if (file.isDirectory()) {
                        details = "[" + details + "]";
                    }
                    details += "\t\t" + file.getSize();
                    details += "\t\t" + dateFormater.format(file.getTimestamp().getTime());
                    System.out.println(details);
                }

             }

          ftp.logout();

        } catch(IOException e) {
               e.printStackTrace();
        } finally {
          if(ftp.isConnected()) {
            try {
              ftp.disconnect();
            } catch(IOException ioe) {
              // do nothing
            }
          }
        }

教程中未处理的一些要点:

  1. 处理防火墙的被动模式
  2. FTP文件的分页
  3. 检查replyCode