FTP传输文件时出错

时间:2015-12-07 14:33:31

标签: java ftp

我正在尝试在java中运行以下FTP代码,但我收到错误 请帮我识别一下

public class FTPUploadFileDemo {

public static void main(String[] args) {

    String server = "localhost";
    int port = 21;
    String user = "username";
    String pass = "password";

    FTPClient ftpClient = new FTPClient();
    try {

        ftpClient.connect(server, port);
        ftpClient.login(user, pass);
        ftpClient.enterLocalPassiveMode();

        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        // APPROACH #1: uploads first file using an InputStream
        File firstLocalFile = new File("C:/Users/un/workspace/Test.txt");

        String firstRemoteFile = "t1.txt";
        InputStream inputStream = new FileInputStream(firstLocalFile);

        System.out.println("Start uploading first file");
        boolean done = ftpClient.storeFile(firstRemoteFile, inputStream);
        inputStream.close();
        if (done) {
            System.out.println("The first file is uploaded successfully.");
        }


        File secondLocalFile = new File("C:/Users/un/workspace/Test.txt");
        String secondRemoteFile = "t2.txt";
        inputStream = new FileInputStream(secondLocalFile);


        OutputStream outputStream = ftpClient.storeFileStream(secondRemoteFile);
        byte[] bytesIn = new byte[4096];
        int read = 0;

        while ((read = inputStream.read(bytesIn)) != -1) {
            outputStream.write(bytesIn, 0, read);
        }
        inputStream.close();
        outputStream.close();

        boolean completed = ftpClient.completePendingCommand();
        if (completed) {
            System.out.println("The second file is uploaded successfully.");
        }

    } catch (IOException ex) {
        System.out.println("Error: " + ex.getMessage());
        ex.printStackTrace();
    } finally {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}}

以上程序显示以下错误:

错误:连接被拒绝:连接 java.net.ConnectException:连接被拒绝:连接

请指导我如何解决它

1 个答案:

答案 0 :(得分:0)

如果在ftpClient.connect(server, port);上收到此错误消息,则表示您的ftp服务器配置不正确,并且不接受本地连接;你的FTP服务器是本地的还是这个例子?