Ftp not loading file in java?

When I upload a file with the following code, it just writes the file to the destination locally, but the file size is zero. Can someone tell me why this is happening and how to fix it?

import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import java.io.FileOutputStream; import java.io.IOException; public class FtpDownload { public static void main(String[] args) { FTPClient client = new FTPClient(); FileOutputStream fos = null; String filename = "config.zip"; try { client.connect("ftpsrv"); client.login("user", "user"); for (FTPFile file : client.listFiles()) { filename = "C:\\tmp\\user\\" + file.getName(); if (file.isFile()) { fos = new FileOutputStream(filename); client.retrieveFile(filename, fos); System.out.println(file.getName()); } else if (file.isDirectory()) { System.out.println("directory: " + file.getName()); } } } catch (IOException e) { e.printStackTrace(); } finally { try { if (fos != null) { fos.close(); } client.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } } 
+6
source share
3 answers

after searching the Apache documentation, I come to the conclusion that BINARY_FILE_TYPE is not set yet. I have the following code and everything is fine. thanks to all of you that helped.

 try { client.connect(ftpServer); client.login(username, password); // following line fixed my zip file corruption issue. client.setFileType(FTP.BINARY_FILE_TYPE); 
+15
source

You use the local path variable pointing to the remote file:

 filename = "C:\\tmp\\user\\" + file.getName(); ... client.retrieveFile(filename, fos); 

You want to specify the remote file, not the local address, for example:

 client.retrieveFile(file.getName(), fos); 

Also, make sure you close the fos stream after reading each file, and not the right at the end. You can use IOUtils.closeQuietly(fos); for this, if you get a commons.io library that avoids nested try-catch blocks.

You should also use the BINARY file type and BLOCK to transfer ZIP files:

 client.setFileTransferMode(FTPClient.BLOCK_TRANSFER_MODE); client.setFileType(FTPClient.BINARY_FILE_TYPE); 
+4
source

try closing the thread at each iteration in a loop

 fos.close(); 

Your code does not do it right, because you have a for loop that creates a new thread at each iteration, but only closes the last

+1
source

Source: https://habr.com/ru/post/909639/


All Articles