Search code examples
javaftpftp-clientftp-server

.class uploaded on FTP server using FTPClient is corrupted


I am uploading a .class file on FTP server. The uploaded file is not empty but is surely corrupted as I am not able to de-compile it. I suspect there is a different way of uploading .class files on FTP server.

Here is the snippet:

public boolean uploadFileOnFTPServer(File file, String uploadToPath) { 
    //file - File stored on local system that is to be uploaded on server
    //uploadToPath - Remote server path where the file is to be stored

    boolean isUploaded = false;
    try {
        FileInputStream inputStream = new FileInputStream(file);
       //InputStream inputStream = new FileInputStream(file);

        if (connectToFTPServer()) { // connectToFTPServer() - method to connect to server
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); // ftpClient is an object of FTPClient class

            if (ftpClient.login(userName, password)) {
                System.out.println("Logged in to server. Username: " + userName);
                if (ftpClient.changeWorkingDirectory(uploadToPath)) {
                    System.out.println("Navigated to path " + uploadToPath);                                                              

                    if (ftpClient.storeFile(file.getName(), inputStream)) {
                        inputStream.close();
                        System.out.println("File " + file.getName() + " uploaded to server.");
                        isUploaded = true;
                    }

                } 
        }
    } catch (Exception e) {
        strRemarks = "Exception reported: Unable to upload file. Error Details: " + e.toString();
        System.out.println(strRemarks);
        e.printStackTrace();
    } finally {
        disconnectFTPServer();
    }
    return isUploaded;
}

Solution

  • This worked:

    Adding setFileType() after getting connected to server but before transfer of file.

                        ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);                 
                        String remoteFileName = file.getName();
                        if (ftpClient.storeFile(remoteFileName, inputStream)) {
                            inputStream.close();
                            System.out.println("File " + file.getName() + " uploaded to server.");
                            isUploaded = true;
                        }
    

    Thanks a lot EJP :)