Kris
Kris

Reputation: 828

Java FTP upload creates an empty file

When I try to upload a simple text file with the Apache Commons FTPClient and this code:

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?

Upvotes: 3

Views: 6606

Answers (3)

JK Patel
JK Patel

Reputation: 31

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. In fact there are two 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 mode to passive:

    objFtpClient.enterLocalPassiveMode();
    

Upvotes: 2

Kris
Kris

Reputation: 828

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.

Upvotes: 2

Andrew Wilkinson
Andrew Wilkinson

Reputation: 248

You might have to set the FileTranserMode to binary too:

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

Upvotes: 0

Related Questions