Reputation: 295
It turned out I misunderstood what the available() method actually does, so I just altered the code that wrote the data to this:
int b = input.read();
while (b != -1) {
output.write(b);
b = input.read();
}
I'll work on a more efficient reading/writing method another time, for now I'm just glad I've it working. Thanks for the help!
I'm using the Commons-Net library to interact with a server via FTP and I've come across a problem when I try downloading files from the server to the local machine. I don't know if this is a bug in Comments-Net.FTPClient, but it's infinitely more likely I'm just not using the library correctly. That said, I haven't been able to find a solution when I googled the problem and example code I have seen appears to use the same method for downloading files as I do.
Anyway, the actual problem is that some of the files downloaded are completely empty, when they should contain data. It happens at random, so every time I download all the files, different files end up being empty each time. I'm assuming there is a problem with the way I'm reading the data from the server or writing it to a file.
Here's the code:
// For each file
InputStream input = ftp.retrieveFileStream(sourcePath);
ftp.completePendingCommand();
OutputStream output = new FileOutputStream(new File(destinationPath));
while (input.available() > 0) {
output.write(input.read());
}
input.close();
output.close();
I'm pretty new to networking, so am I just being silly and doing something really simple wrong?
Upvotes: 1
Views: 1737
Reputation: 2773
Check out commons-io with IOUtils
and FileUtils
for simpler stream processing
Upvotes: 0
Reputation: 1930
You shouldn't be using input.available() as that just tells you how much input is available without blocking. Loop until end of file instead (i.e. until read() returns -1).
http://download.oracle.com/javase/6/docs/api/java/io/InputStream.html#read()
If efficiency is a concern you could also try reading more than one byte at a time.
Upvotes: 2