2

我在 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;
}
4

2 回答 2

0

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

我还建议指定编码

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

这应该在连接之前完成。

于 2014-04-18T07:53:18.140 回答
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 :)

于 2014-04-18T08:21:28.293 回答