2016-12-15 139 views
0

我试图将文件上传到FTP服务器的Java:将文件上传到FTP服务器

正如我在这里How do you upload a file to an FTP server?发现,我有这样的代码:

FTPClient client = new FTPClient(); 
FileInputStream fis = null; 

try { 
    client.connect("IP"); 
    client.login("user", "pwd"); 
    client.changeWorkingDirectory("https://stackoverflow.com/a/b/c/"); 

    // Create an InputStream of the file to be uploaded 
    String filePath = file.getPath(); 
    fis = new FileInputStream(filePath); 
    String fileName = file.getName();        

    // Store file to server 
    client.storeFile(fileName, fis); 
    client.logout(); 

} catch (Exception e) { 
    e.printStackTrace(); 
} finally { 
    try { 
    if (fis != null) { 
     fis.close(); 
    } 
    client.disconnect(); 
    } catch (Exception e) { 
    e.printStackTrace(); 
    } 
} 

当我运行它,创建文件,其中预期,但它是空的(0 KB)

的写作过程也需要相当多的时间...

我在做什么错?

+0

查看这段代码是否正确:String filePath = file.getPath(); fis = new FileInputStream(filePath);你如何创建文件对象?它可能会很慢,因为你的互联网连接速度慢或者你的ftp服务器很慢......可能是 – thepaulo

+0

任何错误/异常? –

+0

您可以使用独立的FTP客户端将相同的文件上传到同一个服务器和目录吗? –

回答

-1

看这篇文章 Apache Commons FTP problems 你需要设置文件类型和tranfor模式来使这项工作。

+0

是什么让你认为错误的传输模式会导致上传的文件变空? –

+0

我已添加文件类型(BINARY_FILE_TYPE)和转移模式(STREAM_TRANSFER_MODE),但问题仍然存在 – Maik