0

I am using commans.net api in order to perform tasks e.g uploading and downloading files from the ftp server. I can perform those tasks successfully but the downloaded files are corrupted. i couldn't open those files in usual manner. please help me..

my simple code look like

    public class FTPConnect {

public static void main(String[] args) {
    startServer();

    connectClient();

}

private static void startServer() {

    FtpServerFactory serverFactory = new FtpServerFactory();

    ListenerFactory factory = new ListenerFactory();
    factory.setPort(21);// set the port of the listener (choose your desired
                        // port, not 1234)
    System.out.println("port has been set to 21");
    serverFactory.addListener("default", factory.createListener());
    PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();
    userManagerFactory.setFile(new File("lib/users.properties"));

    System.out.println("users.properties has been set..");
    userManagerFactory.setPasswordEncryptor(new PasswordEncryptor() {

                @Override
                public String encrypt(String password) {
                    return password;
                }

                @Override
                public boolean matches(String passwordToCheck,
                        String storedPassword) {
                    return passwordToCheck.equals(storedPassword);
                }
            });
    System.out.println("password has been encrypted...");
    BaseUser user = new BaseUser();
    user.setName("java");
    user.setPassword("shiva.dave");
    System.out.println("password has been set..to java and shiva.dave");
    user.setHomeDirectory("lib");
    System.out.println("home directory has been set...");
    List<Authority> authorities = new ArrayList<Authority>();
    authorities.add(new WritePermission());
    user.setAuthorities(authorities);
    UserManager um = userManagerFactory.createUserManager();
    try {
        um.save(user);// Save the user to the user list on the filesystem
        System.out.println("user has been set to the filesystem..");
    } catch (FtpException e1) {
        e1.printStackTrace();
    }
    serverFactory.setUserManager(um);
    FtpServer server = serverFactory.createServer();
    try
    {
        server.start();//Your FTP server starts listening for incoming FTP-connections, using the configuration options previously set
        System.out.println("Server has been started.....");
    }
    catch (FtpException ex)
    {
      ex.printStackTrace();
    }

}

private static void connectClient() {

    FTPClient client = new FTPClient();
    try{
        client.connect(InetAddress.getLocalHost(), 21);
        String loging_success = client.login("java", "shiva.dave") == true ? "success" : "failed";
        System.out.println("login: " + loging_success);
        FTPFile[] clients = client.listFiles("/");
        System.out.println("Listed " + clients.length + " files.");
        for (FTPFile file : clients) {
            System.out.println(file.getName());
        }

        for (FTPFile ftpFile : clients) {
            String remoteFile2 = ftpFile.getName();
            File downloadFile2 = new File("D:/test2/"+ftpFile.getName());
            OutputStream outputStream2 = new BufferedOutputStream(new FileOutputStream(downloadFile2));
            InputStream inputStream = client.retrieveFileStream(remoteFile2);
            byte[] bytesArray = new byte[4096];
            int bytesRead = -1;
            while ((bytesRead = inputStream.read(bytesArray)) != -1) {
                outputStream2.write(bytesArray, 0, bytesRead);
            }

            boolean success = client.completePendingCommand();
            if (success) {
                System.out.println("File #2 has been downloaded successfully.");
            }
            outputStream2.close();
            inputStream.close();
        }

    }
    catch(Exception e){
        e.printStackTrace();
    }
    finally{
        try{
            client.logout();
            client.disconnect();
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }

}
}
user2428568
  • 223
  • 1
  • 4
  • 18

1 Answers1

2

I founded a solution and want to put that here.. first of all when you try to download files from the ftp server you must need to specify the file type and transfer mode in order to download file successfully.

here is the code you need to insert.

client.setFileType(FTP.BINARY_FILE_TYPE, FTP.BINARY_FILE_TYPE); client.setFileTransferMode(FTP.BINARY_FILE_TYPE);

"WATCH IT GUYS"

you must need to insert these two lines of code after successfully logged in otherwise you wouldn't be able to download files successfully...

Hope this answer will help you to download files without being corrupted..

user2428568
  • 223
  • 1
  • 4
  • 18
  • 1
    Here is the doc to check all the file type and modes : https://commons.apache.org/proper/commons-net/apidocs/constant-values.html#org.apache.commons.net.ftp.FTP.RECORD_STRUCTURE – Gaurav Khare Dec 29 '17 at 06:20