使用FTPClient在远程目录中文件上传失败,如果该文件已经存在于远程目录中,则附加时间戳并上传

时间:2018-10-04 10:05:14

标签: java ftp-client

首先检查文件是否存在于远程目录中,如果已存在,则将当前时间戳附加到文件中,然后上传。下面是代码段。

输出: 添加了时间戳的新文件名:somefile_2018-10-04.txt

当前目录:空

上传失败!

我能够弄清楚。帮助将不胜感激。 预先感谢。

protected boolean connect() {
    if(!ftpClient.isConnected()) {
        try {
            ftpClient.connect(host, port);

            if(!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                ftpClient.disconnect();
                System.err.println("Error in connection!!");
                return false;
            }

            if(!ftpClient.login(username, password)) {
                ftpClient.disconnect();
                System.err.println("Failed to login!!");
                return false;
            }

            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();

        } catch (IOException e) {
            disconnect();
            e.printStackTrace();
        }
    }
    return true;
}

protected boolean check(String dir, String filename) throws IOException {
    InputStream inputStream = ftpClient.retrieveFileStream(filename);
    if (inputStream == null || ftpClient.getReplyCode() == 550)
        return false;
    return true;
}


protected String copyIfExists(String dir, String filename) throws IOException {
    if(check(dir, filename)) {
        int index            = filename.lastIndexOf(".");
        if(index != -1) {
            String fname     = filename.substring(0, index);
            String extension = filename.substring(index);
            SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
            String timeStamp = dateformat.format(new Timestamp(System.currentTimeMillis()));
            filename         = fname.concat("_" + timeStamp + extension);
            System.out.println("New file name with timestamp appended: " + filename);
            return filename;
        } else 
            System.out.println("Invalid file name");
    }
    return filename;
}


public boolean upload(String srcDir, String destDir, String filename) {
    if(connect()) {
        try(InputStream inputStream = new FileInputStream(new File(srcDir + filename))) {

            ftpClient.changeWorkingDirectory(destDir);
            filename = copyIfExists(destDir, filename);

            // It's printing null here
            System.out.println("Current Dir: " + ftpClient.printWorkingDirectory());

            if(ftpClient.storeFile(filename, inputStream)) {
                System.out.println("File uploaded successfully!!");
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            disconnect();
        }
    }
    System.out.println("Upload failed!");
    return false;
}

0 个答案:

没有答案