tags:

views:

43

answers:

1

Hi, I have this little piece of code below which uploads a file in java, the code functions correctly however it hangs for a long time when opening the output stream.

// open file to upload
InputStream filein = new FileInputStream("/path/to/file.txt");

// connect to server
URL url = new URL("ftp://user:pass@host/dir/file.txt");
URLConnection urlConn = url.openConnection();
urlConn.setDoOutput(true);

// write file

// HANGS FROM HERE
OutputStream ftpout = urlConn.getOutputStream();
// TO HERE for about 22 seconds

byte[] data = new byte[1024];
int len = 0;

while((len = filein.read(data)) > 0) {
ftpout.write(data,0, len);
}

// close file                   
filein .close();
ftpout.close();

In this example the URLConnection.getOutputStream() method hangs for about 22 seconds before continuing as normal, the file is successfully uploaded. The file is only 4 bytes in this case, just a text file with the word 'test' in it and the code hangs before the upload commences so its not because its taking time to upload the file.

This is only happening when connecting to one server, when I try a different server its as fast I could hope for which leads me to think it is a server configuration issue in which case this question may be more suited to server fault, however if I upload from an FTP client (in my case FileZilla) it works fine so it could be there is something I can do with the code to fix this.

Any ideas?

A: 

I have solved the problem by switching to use the Commons Net FTPClient which does not apear to have the same problems which changes the code to this below.

            InputStream filein = new FileInputStream(new File("/path/to/file.txt"));

            // create url
    FTPClient ftp = new FTPClient();
    ftp.connect(host);
    ftp.login(user, pass);

    int reply = ftp.getReplyCode();
    if(!FTPReply.isPositiveCompletion(reply)) {
        ftp.disconnect();
        System.err.println("FTP server refused connection.");
        return;
    }

    OutputStream ftpout = ftp.appendFileStream("text.txt");

    // write file
    byte[] data = new byte[1024];
    int len = 0;

    while((len = filein.read(data)) > 0) {
        ftpout.write(data,0, len);
    }

    filein.close();
    ftpout.close();
    ftp.logout();
murdoch