java怎么读取ftp上的文件

39次阅读
没有评论

共计 1599 个字符,预计需要花费 4 分钟才能阅读完成。

要读取 FTP 上的文件,您可以使用 Java 的 FTP 客户端库,如 Apache Commons Net 库。以下是一个示例代码,演示如何使用 Apache Commons Net 连接到 FTP 服务器并读取文件:

  1. 首先,您需要在项目中导入 Apache Commons Net 库。您可以从官方网站上下载并将其添加到项目的依赖项中。

  2. 接下来,您可以使用以下代码连接到 FTP 服务器并读取文件:

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class FTPExample {public static void main(String[] args) {String server = "ftp.example.com";
        int port = 21;
        String username = "your-username";
        String password = "your-password";
        String remoteFile = "/path/to/remote-file.txt";
        String localFile = "local-file.txt";

        FTPClient ftpClient = new FTPClient();
        try {ftpClient.connect(server, port);
            ftpClient.login(username, password);
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

            OutputStream outputStream = new FileOutputStream(localFile);
            boolean success = ftpClient.retrieveFile(remoteFile, outputStream);
            outputStream.close();

            if (success) {System.out.println("File downloaded successfully.");
            } else {System.out.println("File download failed.");
            }
        } catch (IOException e) {e.printStackTrace();
        } finally {try {if (ftpClient.isConnected()) {ftpClient.logout();
                    ftpClient.disconnect();}
            } catch (IOException e) {e.printStackTrace();
            }
        }
    }
}

在上面的示例代码中,您需要替换以下变量的值:

  • server:FTP 服务器的主机名或 IP 地址。
  • port:FTP 服务器的端口号(通常为 21)。
  • username:用于登录的 FTP 用户名。
  • password:用于登录的 FTP 密码。
  • remoteFile:要从 FTP 服务器读取的远程文件的路径。
  • localFile:将远程文件保存到本地的路径。

在代码中,我们首先创建一个 FTPClient 对象,然后使用 connect 方法连接到 FTP 服务器。接下来,我们使用 login 方法进行身份验证,并使用 enterLocalPassiveMode 方法进入被动模式。然后,我们使用 setFileType 方法设置文件类型为二进制。然后,我们创建一个 FileOutputStream 来保存下载的文件,并使用 retrieveFile 方法从 FTP 服务器下载文件。最后,我们使用 logoutdisconnect方法断开与 FTP 服务器的连接。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-13发表,共计1599字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)