Search code examples
javavimvimdiff

How to execute vimdiff command from inside a java program


I have a list of files for which I have to run the vimdiff command and save the output as a html file.I am doing this with Java. Below is the command I am trying to execute

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!'"

When I run the below code, the code is getting executed. But I am not able to see the file getting generated.

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

The command is running fine when executed from a terminal. But its not working when executed inside a java program. Can someone help me with this issue? I did a lot of search but not able to proceed with this.


Solution

  • After Two days I found the below Solution:

    I added the vimdiff command to a shell script and executed it using the following method and it worked like a gem.

    Java method

    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' $1 $2 -c TOhtml -c 'w! '"$3"'' -c 'qa!'
    

    Note:

    • file1 will be passed as a argument in the place of $1
    • file2 will be passed as a argument in the place of $2
    • outputfile will be passed as a argument in the place of $3