Java URLConnection使用FTP url调用getOutputStream的速度很慢

Java URLConnection使用FTP url调用getOutputStream的速度很慢,java,ftp,Java,Ftp,我有一段代码,下面用java上传了一个文件,代码运行正常,但是在打开输出流时会挂起很长时间 // 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.openConnecti

我有一段代码,下面用java上传了一个文件,代码运行正常,但是在打开输出流时会挂起很长时间

// 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();
在本例中,URLConnection.getOutputStream()方法挂起约22秒,然后继续正常操作,文件已成功上载。在本例中,该文件只有4个字节,只是一个文本文件,其中包含单词“test”,并且代码在上传开始之前挂起,因此这不是因为上传文件需要时间

只有当连接到一台服务器时才会发生这种情况,当我尝试另一台服务器时,我希望它能以最快的速度运行,这让我认为这是一个服务器配置问题,在这种情况下,这个问题可能更适合于服务器故障,但是如果我从FTP客户端上传(在我的例子中是FileZilla)它工作得很好,所以我可以用代码来解决这个问题


有什么想法吗?

我通过切换到Commons Net FTPClient解决了这个问题,它不会出现与下面代码相同的问题

            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();

我已经通过切换到使用Commons Net FTPClient解决了这个问题,它不会出现与下面的代码相同的问题

            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();