Friday, January 21, 2011

FTP in Java to an IFS folder

A couple of years ago I wrote about uploading files via FTP to a remote server, ending the post reminding about the Commons Net library. Well, the time has come for me to use it, having to upload a file to an IFS folder.

The naive approach didn't work:
@Test
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();
}
as 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:
@Test
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();
}
Obviously 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.

1 comment:

for IT the said...

Java Standard Edition Java Enterprise Edition Certification Training Course ware Java Training in Chennai . Java Development Kit JDK J2EE Training in Chennai Java Runtime Environment JRE Java Course in Chennai on Linux Java Interview Questions . IT Technical Articles Java SE Java EE Java Online Course Oracle Learning Tutorials. Java EE Training Java is a great cross-platform programming language. Java EE & Java SE Java Training Institutes in Chennai on Linux Training Course Materials. java j2ee training institutes in chennai