FTP上のファイルをJavaで読み込む方法
FTP 上のファイルを扱うには Java の FTP クライアントのライブラリ (Apache Commons Net など) が使用できます。以下は Apache Commons Net を使って FTP サーバに接続してファイルをダウンロードするコードの例です:
- 首先,您需要在项目中导入Apache Commons Net库。您可以从官方网站上下载并将其添加到项目的依赖项中。
- 次に、次のコードを使用して 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();
}
}
}
}
在上面的示例代码中,您需要替换以下变量的值:
- FTPサーバーのホスト名、またはIPアドレス。
- port:FTPサーバーのポート番号(通常は21)
- FTPにログインするためのユーザー名。
- パスワード:FTPへログインする際のパスワード。
- FTPサーバから読み込むリモートファイルのパス
- localFile:将远程文件保存到本地的路径。
コードでは、まずFTPClientオブジェクトを作成し、connectメソッドを用いてFTPサーバに接続します。次に、loginメソッドで認証を行い、enterLocalPassiveModeメソッドを用いてパッシブモードに移行します。その後、setFileTypeメソッドでファイルタイプをバイナリに設定します。続いて、FileOutputStreamを作成してダウンロードファイルを保持し、retrieveFileメソッドを用いてFTPサーバからファイルをダウンロードします。最後に、logoutとdisconnectメソッドを用いてFTPサーバとの接続を解除します。