使用rsync4j库,一个Linux rsync工具的Java实现,如何将远程目录中的数据与本地目录同步



我需要Java程序中类似rsynclinux工具的功能。为此,我选择了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后,程序被卡住。既不会引发异常,也不会继续执行程序

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

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

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

最新更新