Question
How can I upload a file using FTPClient in Java?
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
Answer
Using the FTPClient class from the Apache Commons Net library allows Java developers to easily connect to FTP servers and perform file uploads. This process involves establishing a connection, logging in with credentials, setting the file type, and finally uploading the file.
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
public class FTPUploader {
public static void main(String[] args) {
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect("ftp.example.com");
ftpClient.login("username", "password");
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
FileInputStream inputStream = new FileInputStream("local-file.txt");
boolean done = ftpClient.storeFile("remote-file.txt", inputStream);
inputStream.close();
if (done) {
System.out.println("File uploaded successfully.");
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Causes
- Incorrect server address
- Wrong username or password
- Insufficient permissions on the server
- Network connectivity issues
Solutions
- Ensure the FTP server address is correct.
- Double-check the username and password for authentication.
- Verify permissions for the target directory on the server.
- Check your firewall or network configuration for potential blocks.
Common Mistakes
Mistake: Not closing the input stream after the upload.
Solution: Use a try-with-resources statement or close the FileInputStream in a finally block.
Mistake: Forgetting to set the file type before upload.
Solution: Always set the file type using ftpClient.setFileType(FTP.BINARY_FILE_TYPE); for binary files.
Mistake: Using wrong file paths or names.
Solution: Ensure the local file path and remote file name are correct.
Helpers
- Java FTP upload
- FTPClient example Java
- upload files Java
- Apache Commons FTP
- Java networking