使用FTPClient上传到FTP服务器上的.class已损坏

时间:2014-04-18 07:37:01

标签: java ftp ftp-client ftp-server

我正在FTP服务器上传一个.class文件。上传的文件不是空的,但肯定已损坏,因为我无法对其进行反编译。我怀疑在FTP服务器上上传.class文件有不同的方式。

以下是摘录:

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;
}

2 个答案:

答案 0 :(得分:0)

您是否尝试过以二进制模式上传文本文件以查看实际传输的内容?

我还建议指定编码

client.setControlEncoding(encoding);
client.connect(host, port);

应该在连接之前完成。

答案 1 :(得分:0)

这有效:

在连接到服务器之后但在传输文件之前添加setFileType()。

                    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;
                    }

非常感谢EJP:)

相关问题