My goal is to be able to upload files to FTP server, I have researched a bit and saw the way how to upload a file if the file is already stored locally, I have a function that returns byte[]
so I am wondering how to send that file to FTP server if it file exist in memory.
private void connect() throws IOException {
FTPClient ftpClient = new FTPClient();
ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
ftpClient.connect(ftp.getServer(), ftp.getPort());
int reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
throw new RuntimeException("Could not connect to FTP Server");
} else {
ftpClient.login(ftp.getUser(), ftp.getPassword());
}
}
You seem to be using Apache Commons Net FTPClient
.
It actually does not even have a direct way to upload a physical file. Its FTPClient.storeFile
method only accepts InputStream
interface.
Normally you would use FileInputStream
to refer to a physical file:
How do you upload a file to an FTP server?
While you want to to use ByteArrayInputStream
:
Can we convert a byte array into an InputStream in Java?
InputStream inputStream = new ByteArrayInputStream(bytes);
ftpClient.storeFile(remotePath, inputStream);