使用rsync4j库(Linux rsync工具的Java实现)如何将远程目录中的数据与本地目录进行同步

时间:2018-10-26 10:23:32

标签: java rsync librsync

我需要Java程序中类似 rsync linux工具的功能。为此,我选择了rsync4j library

使用他们的documentation,我编写了以下程序:

import com.github.fracpete.processoutput4j.output.ConsoleOutputProcessOutput;
import com.github.fracpete.rsync4j.RSync;

public class MainClass {

    public static void main(String [] args) {

        System.out.println("Started");//check

        RSync rsync = new RSync()
            .source("/home/arth/DataSourceFolder/a.txt")
            .destination("/home/arth/DataDestinationFolder/")
            .recursive(true);
            // or if you prefer using commandline options:
            // rsync.setOptions(new String[]{"-r", "/one/place/", "/other/place/"});
            CollectingProcessOutput output = null;
            try {
                    System.out.println("Inside try");
                    output = rsync.execute();
                    System.out.println("End of try");
            } catch (Exception e) {
                    e.printStackTrace();
            }
            System.out.println(output.getStdOut());
            System.out.println("Exit code: " + output.getExitCode());
            if (output.getExitCode() > 0)
                System.err.println(output.getStdErr());
      }
}

在摘要中,在本地计算机中,文件a.txt从一个位置复制到另一个位置。这很完美。运行该文件后,该文件已成功复制,输出如下:

Started

Inside try

End of try

Exit code: 0

但是我需要将本地目录与远程主机/计算机上的目录同步。当我尝试使用以下命令从终端使用简单的rsync命令执行此操作

rsync remoteUserName@23.24.25.244:/home/beth/remoteFolder/a.png /home/arth/DataSourceFolder

它就像一种魅力。 a.png是按指定的路径复制到本地计算机的,尽管首先要求输入远程计算机的密码。

但是当我使用上述Java程序执行相同的操作时,问题出在,将#11和12行替换为:

.source("remoteUserName@23.24.25.244:/home/beth/remoteFolder/a.png")
.destination("/home/arth/DataDestinationFolder/")

在控制台中打印Started后,程序卡住了。既不会引发异常,也不会继续执行程序。

问题是如何解决此问题?

1 个答案:

答案 0 :(得分:0)

(我知道这是旧文章,但在这里...)rsync4j库不允许进行交互。在您的情况下,底层rysnc二进制文件会在Java库创建的过程中提示输入密码,但永远不会收到密码。 您应该可以使用USER:PASSWORD@HOST/DIR格式来实现自己的目标。