久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

java - 如何將FTP服務器上的文件復制到Java中同一服

How to copy a file on the FTP server to a directory on the same server in Java?(java - 如何將FTP服務器上的文件復制到Java中同一服務器上的目錄?)
本文介紹了java - 如何將FTP服務器上的文件復制到Java中同一服務器上的目錄?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

我正在使用 Apache Commons FTP 上傳文件.在上傳之前,我想檢查該文件是否已存在于服務器上,并將其備份到同一服務器上的備份目錄中.

I'm using Apache Commons FTP to upload a file. Before uploading I want to check if the file already exists on the server and make a backup from it to a backup directory on the same server.

有人知道如何將文件從 FTP 服務器復制到同一服務器上的備份目錄嗎?

public static void uploadWithCommonsFTP(File fileToBeUpload){
    FTPClient f = new FTPClient();
    FTPFile backupDirectory;
    try {
        f.connect(server.getServer());
        f.login(server.getUsername(), server.getPassword());
        FTPFile[] directories = f.listDirectories();
        FTPFile[] files = f.listFiles();
        for(FTPFile file:directories){
            if (!file.getName().equalsIgnoreCase("backup")) {
                backupDirectory=file;
            } else {
               f.makeDirectory("backup");
            }
        }
        for(FTPFile file: files){
            if(file.getName().equals(fileToBeUpload.getName())){
                //copy file to backupDirectory
            }
        }

    } catch (IOException e) {
        e.printStackTrace();
    }

}

<小時>

編輯代碼:還是有問題,當我備份 zip 文件時,備份的文件已損壞.


Edited code: still there is a problem, when i backup zip file, the backup-ed file is corrupted.

有人知道原因嗎?

 public static void backupUploadWithCommonsFTP(File fileToBeUpload) {
    FTPClient f = new FTPClient();
    boolean backupDirectoryExist = false;
    boolean fileToBeUploadExist = false;
    FTPFile backupDirectory = null;
    try {
        f.connect(server.getServer());
        f.login(server.getUsername(), server.getPassword());
        FTPFile[] directories = f.listDirectories();
        // Check for existence of backup directory
        for (FTPFile file : directories) {
            String filename = file.getName();
            if (file.isDirectory() && filename.equalsIgnoreCase("backup")) {
                backupDirectory = file;
                backupDirectoryExist = true;
                break;
            }
        }
        if (!backupDirectoryExist) {
            f.makeDirectory("backup");
        }
        // Check if file already exist on the server
        f.changeWorkingDirectory("files");
        FTPFile[] files = f.listFiles();
        f.changeWorkingDirectory("backup");
        String filePathToBeBackup="/home/user/backup/";
        String prefix;
        String suffix;
        String fileNameToBeBackup;
        FTPFile fileReadyForBackup = null;
        f.setFileType(FTP.BINARY_FILE_TYPE);
        f.setFileTransferMode(FTP.BINARY_FILE_TYPE);
        for (FTPFile file : files) {
            if (file.isFile() && file.getName().equals(fileToBeUpload.getName())) {
                prefix = FilenameUtils.getBaseName(file.getName());
                suffix = ".".concat(FilenameUtils.getExtension(file.getName()));
                fileNameToBeBackup = prefix.concat(Calendar.getInstance().getTime().toString().concat(suffix));
                filePathToBeBackup = filePathToBeBackup.concat(fileNameToBeBackup);
                fileReadyForBackup = file;
                fileToBeUploadExist = true;
                break;
            }
        }
        // If file already exist on the server create a backup from it otherwise just upload the file.
        if(fileToBeUploadExist){
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            f.retrieveFile(fileReadyForBackup.getName(), outputStream);
            InputStream is = new ByteArrayInputStream(outputStream.toByteArray());
            if(f.storeUniqueFile(filePathToBeBackup, is)){
                JOptionPane.showMessageDialog(null, "Backup succeeded.");
                f.changeWorkingDirectory("files");
                boolean reply = f.storeFile(fileToBeUpload.getName(), new FileInputStream(fileToBeUpload));
                if(reply){
                    JOptionPane.showMessageDialog(null,"Upload succeeded.");
                }else{
                    JOptionPane.showMessageDialog(null,"Upload failed after backup.");
                }
            }else{
                JOptionPane.showMessageDialog(null,"Backup failed.");
            }
        }else{
            f.changeWorkingDirectory("files");
            f.setFileType(FTP.BINARY_FILE_TYPE);
            f.enterLocalPassiveMode();
            InputStream inputStream = new FileInputStream(fileToBeUpload);
            ByteArrayInputStream in = new ByteArrayInputStream(FileUtils.readFileToByteArray(fileToBeUpload));
            boolean reply = f.storeFile(fileToBeUpload.getName(), in);
            System.out.println("Reply code for storing file to server: " + reply);
            if(!f.completePendingCommand()) {
                f.logout();
                f.disconnect();
                System.err.println("File transfer failed.");
                System.exit(1);
            }
            if(reply){

                JOptionPane.showMessageDialog(null,"File uploaded successfully without making backup." +
                        "
Reason: There wasn't any previous version of this file.");
            }else{
                JOptionPane.showMessageDialog(null,"Upload failed.");
            }
        }
        //Logout and disconnect from server
        in.close();
        f.logout();
        f.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

推薦答案

如果你使用的是 apache commons net FTPClient,有一個直接的方法可以將文件從一個位置移動到另一個位置(如果user 有適當的權限).

If you are using apache commons net FTPClient, there is a direct method to move a file from one location to another location (if the user has proper permissions).

ftpClient.rename(from, to);

或者,如果你熟悉 ftp 命令,你可以使用類似

or, If you are familiar with ftp commands, you can use something like

ftpClient.sendCommand(FTPCommand.yourCommand, args);
if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
     //command successful;
} else {
     //check for reply code, and take appropriate action.
}

如果您使用任何其他客戶端,請閱讀文檔,客戶端實現之間不會有太大變化.

If you are using any other client, go through the documentation, There wont be much changes between client implementations.

更新:

上述方法將文件移動到 to 目錄,即該文件將不再存在于 from 目錄中.基本上 ftp 協議意味著從 local <-> 傳輸文件.遠程遠程<->其他遠程,但不能在服務器中傳輸.

Above approach moves the file to to directory, i.e, the file won't be there in from directory anymore. Basically ftp protocol meant to be transfer the files from local <-> remote or remote <-> other remote but not to transfer with in the server.

這里的工作會更簡單,將完整的文件獲取到本地 InputStream 并將其作為備份目錄中的新文件寫回服務器.

The work around here, would be simpler, get the complete file to a local InputStream and write it back to the server as a new file in the back up directory.

要獲取完整的文件,

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ftpClient.retrieveFile(fileName, outputStream);
InputStream is = new ByteArrayInputStream(outputStream.toByteArray());

現在,將此流存儲到備份目錄.首先,我們需要將工作目錄更改為備份目錄.

now, store this stream to backup directory. First we need to change working directory to backup directory.

// assuming backup directory is with in current working directory
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);//binary files
ftpClient.changeWorkingDirectory("backup");
//this overwrites the existing file
ftpClient.storeFile(fileName, is);
//if you don't want to overwrite it use storeUniqueFile

希望對你有所幫助..

這篇關于java - 如何將FTP服務器上的文件復制到Java中同一服務器上的目錄?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

How to wrap text around components in a JTextPane?(如何在 JTextPane 中的組件周圍環繞文本?)
MyBatis, how to get the auto generated key of an insert? [MySql](MyBatis,如何獲取插入的自動生成密鑰?[MySql])
Inserting to Oracle Nested Table in Java(在 Java 中插入 Oracle 嵌套表)
Java: How to insert CLOB into oracle database(Java:如何將 CLOB 插入 oracle 數據庫)
Why does Spring-data-jdbc not save my Car object?(為什么 Spring-data-jdbc 不保存我的 Car 對象?)
Use threading to process file chunk by chunk(使用線程逐塊處理文件)
主站蜘蛛池模板: 中日字幕大片在线播放 | 国产黑丝av| 亚洲欧美一区二区三区国产精品 | 亚洲国产成人av好男人在线观看 | 欧美激情精品久久久久久变态 | 凹凸日日摸日日碰夜夜 | 日本大香伊一区二区三区 | 在线观看涩涩视频 | 日韩成人在线视频 | 亚洲福利一区二区 | 玖玖精品| 男人天堂网址 | 99久久亚洲 | 国产精品久久国产精品久久 | 蜜臀久久 | 久久国产视频网站 | 欧美日韩看片 | 在线亚洲一区 | 性色视频 | 亚洲精品日韩一区二区电影 | 亚洲天堂成人在线视频 | 羞羞在线观看视频 | 国产亚洲一区精品 | 国产精品1区2区3区 男女啪啪高潮无遮挡免费动态 | 亚洲劲爆av | 精品国产乱码久久久久久影片 | 久久精品色欧美aⅴ一区二区 | av影音资源 | 国外成人在线视频 | 国产一区二区三区网站 | 久久逼逼 | 国产中文字幕网 | 精品欧美一区免费观看α√ | 黄色欧美在线 | h视频亚洲 | 1000部精品久久久久久久久 | 91日韩在线 | 成人av看片| 男女污污动态图 | 日韩欧美一级片 | 在线成人福利 |