i'm currently working on a small checklist builder program in Java. I would like to upload and download the created file to my FTP Server (ftps). I'm using the following code for downloading:
public static void downloadfile(){
FTPSClient con = null;
System.out.println("Download Status: 5%");
try
{
System.out.println("Download Status: 20%");
con = new FTPSClient();
con.connect(url);
if (con.login(user, psw))
{
System.out.println("Download Status: 50%");
con.enterLocalPassiveMode(); // important!
con.setFileType(FTP.BINARY_FILE_TYPE);
String data = "E:\\Downloads\\Testdokument.txt";
OutputStream out = new FileOutputStream(new File(data));
boolean result = con.retrieveFile("Testdokument.txt", out);
out.close();
System.out.println(result);
if (result) {
System.out.println("Download Status: 100%");
} else if(result == false) {
System.out.println("Download won't work");
}
con.logout();
con.disconnect();
}
}
catch (Exception e)
{
System.out.println("download failed");
e.printStackTrace();
}
}
the problem is that the download itself works fine. But the downloaded file is empty. If i try it with an Image it isn't "readable". The upload instead works perfectly. I use the Apache Common IO Library for the FTP function.
If i download the file the console shows first status 5%, 20%, 50% and than, after adding the false statement, Download won't work ...
I have no idea why the file itself is downloading but not including any content.
Any ideas?
You're not doing resources in java correctly.
Anytime you create an object that represents a resource, you must close it. You open a new FileOutputStream
, and that is a resource. Anything that implements AutoCloseable
is definitely a resource that you must close. Try this:
try (OutputStream out = new FileOutputStream(data /* no need to wrap in File */)) {
// do your stuff with out here
}
Second note: Your exception handling is atrocious; please stop making this common mistake. Exceptions contain 4 useful bits of information: Type, Message, Trace, and Cause. You're literally tossing 3 out of the 4 into the bin. Just add throws Exception
to your main method, and your downloadFile
method. It saves you typing and makes your error messages much more useful.