java FTP upload creates empty file

2019-01-25 23:07发布

问题:

When I try to upload a simple text file with the apache commons ftpClient and this code:

imports*

public class ftpUpload {

public static void main(String[] args) {

    FTPClient ftp = new FTPClient();
    int reply;

    // connect
    try {

        ftp.connect(serverAdd);
        ftp.login(username,password);
        reply = ftp.getReplyCode();

        if(FTPReply.isPositiveCompletion(reply)){
            System.out.println("Connected Success..");

            // upload file
            try {
                String fileDir = "testfile.txt";
                FileInputStream in = null;       
                in = new FileInputStream(fileDir);     
                ftp.storeFile(fileDir,in);
                System.out.println("File upload complete..");
            }catch(IOException e){
                System.out.println(e);
            }

            ftp.disconnect();
            System.out.println("Disconnected..");

        }else {
            System.out.println("Connection Failed..");
            ftp.disconnect();
        }   

    } catch (SocketException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
  }
}

A file gets created in the root of the FTP server but it is empty. what´s wrong? I already tried to change the ftp mode to BINARY when uploading a PDF file. but the file is also 0 in size.

ftp.setFileType(FTP.BINARY_FILE_TYPE);

I also only want to upload a bunch of txt files, so the default ascii mode should be fine, right?

回答1:

ok, it seems that it is a probem with my firewall. when I deactivate the firewall the file gets written to the ftp with no problem.



回答2:

I was having the same problem. The file created but size 0 KB. after setting mode to passive, my file successfully transferred to FTP Server. Infact there are 3 things we have to take care while uploading file on FTP Server.

1). set file type to BINARY

objFtpClient.setFileType(FTP.BINARY_FILE_TYPE);

2). set File Transfer Mode to BINARY

objFtpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);

3). set Mode to Passive (i dont know what it does internally. but it works...!)

objFtpClient.enterLocalPassiveMode();


回答3:

You might have to set the FileTranserMode to binary too:

ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.setFileTransferMode(FTP.BINARY_FILE_TYPE);


标签: java ftp