The naive approach didn't work:
@Testas it returned the "550-Specified library does not exist or cannot be accessed." error. Too bad. After some investigations we found that before we could access the folder we were interested in we had to issue the "cd /" command. All right, I went for the commons:
public void basicTest() throws Exception {
URL url = new URL("ftp://user:pass@remoteserver/path/to/remote/folder/" + "outputFile.txt");
URLConnection urlc = url.openConnection();
OutputStream outputStream = urlc.getOutputStream();
String text = "oooooo sooooleee miiiiiiiooooooo.....";
InputStreamReader reader = new InputStreamReader(IOUtils.toInputStream(text));
int mychar = reader.read();
while (mychar != -1) {
outputStream.write(mychar);
mychar = reader.read();
}
reader.close();
outputStream.close();
}
@TestObviously this code is simplistic and pretends that errors cannot happen, but it's just to grab the sense of it. We create an instance of the FTPClient class and connect to our remote server (after all we are dealing with sockets... does that ring a bell?), then we use the normal FTP commands to reach the folder we need. After getting an OutputStream, obtained with the storeFileStream(String filename) method, we do everything like in the previous example, then log out and disconnect from the server.
public void commonsTest() throws Exception {
FTPClient ftp = new FTPClient();
ftp.connect("remoteserver");
ftp.login("user", "pass");
ftp.changeWorkingDirectory("/");
ftp.changeWorkingDirectory("path/to/remote/folder");
OutputStream outputStream = ftp.storeFileStream("outputFile.txt");
String text = "oooooo sooooleee miiiiiiiooooooo.....";
InputStreamReader reader = new InputStreamReader(IOUtils.toInputStream(text));
int mychar = reader.read();
while (mychar != -1) {
outputStream.write(mychar);
mychar = reader.read();
}
reader.close();
outputStream.close();
ftp.logout();
ftp.disconnect();
}
No comments:
Post a Comment