1

我需要像rsync我的 Java 程序中的 linux 工具那样的功能。为此,我选择了rsync4j 库

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

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在控制台中打印后程序卡住了。既不会引发异常,程序也不会继续执行。

问题是我该如何解决这个问题?

4

1 回答 1

1

(旧帖子,我知道,但在这里......) rsync4j 库不允许交互。在您的情况下,底层 rysnc 二进制文件在 Java 库创建的过程中提示输入密码,但从未收到密码。

从版本3.2.3-7开始,您可以提供sshpass包装器的实例来输入密码(请参阅此注释以获取示例)。

于 2019-04-30T03:13:18.007 回答