如何从 java 程序中执行 vimdiff 命令

How to execute vimdiff command from inside a java program

我有一个文件列表,我必须 运行 vimdiff 命令并将输出保存为 html file.I 我正在使用 Java 执行此操作。下面是我要执行的命令

String cmd = "vimdiff -c 'set foldlevel=9999' src/test/resources/testdata/output/html_output_before_changes/file1.html src/test/resources/testdata/output/html_output_after_changes/file2.html -c TOhtml -c 'w! different.html' -c 'qa!'"

当我运行下面的代码时,代码正在执行。但是我看不到生成的文件。

Runtime rt = Runtime.getRuntime();
Process process = rt.exec(cmd);

从终端执行该命令 运行 没问题。但是在 java 程序中执行时它不起作用。有人可以帮我解决这个问题吗?我做了很多搜索,但无法继续进行。

您正在使用 :TOhtml 并将结果写为 different.html。如果您不确定该文件的位置,请检查 Java 进程的当前工作目录,对您的硬盘进行文件搜索,或者在 Vim 命令中指定一个绝对路径当然。

您不会从 Vim 的操作本身看到任何东西。使用 process.getInputStream(),您 可以 获得 Vim 在终端运行期间写入的内容,但这只是一堆乱码,因为 Vim 使用特殊的 ANSI 转义序列来控制终端、定位光标等。

要非交互使用Vim,建议传递以下选项:

-T dumb           Avoids errors in case the terminal detection goes wrong.
-n                No swapfile.
-i NONE           Ignore the |viminfo| file (to avoid disturbing the
                  user's settings).
-c 'set nomore'   Suppress the more-prompt when the screen is filled
                  with messages or output to avoid blocking.

无法与 Vim 交互(从您的 Java 程序内部),故障排除提示是启用详细日志记录:您可以捕获 Vim 会话的完整日志-V20vimlog。退出 Vim 后,检查 vimlog 日志文件是否有错误。

两天后我找到了以下解决方案:

我将 vimdiff 命令添加到 shell 脚本并使用以下方法执行它,它像 gem.

一样工作

Java方法

try {
            File[] uiDiffDir = getFiles();

            for (File file : uiDiffDir) {

                String[] cmd = {"sh", shellScriptPath, file1, file2,
                        outputfile};
                Process p = Runtime.getRuntime().exec(cmd);
                p.waitFor();
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        p.getInputStream()));
                String line;
                while ((line = reader.readLine()) != null) {
                    System.out.println(line);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

shell.sh

vimdiff -c 'set foldlevel=9999'   -c TOhtml -c 'w! '""'' -c 'qa!'

注:

  • file1 将作为参数传递,代替 $1
  • file2 将作为参数传递,代替 $2
  • outputfile 将作为参数传递,代替 $3