Search code examples
javajarexternal-process

Run a R script from a java jar


I have a java program that calls a R script. Here is the command:

String filename = "hierarchicalClusteringScript.R";
String[] cmd=new String[]{this.conn.getRPath(),"CMD","BATCH",
            "--args LD_matrix='"+LD_matrix+"' " +
            "image_filename='"+image_filename+"' " +
            "width="+300+" "+
            "height="+height+" "+
            "ordered_snps_filename='"+ordered_snps_filename+"'",
            filename,
               this.conn.getWorkingDir()+this.conn.getProjectName()+"Routput.txt"};
    Runtime runtime = Runtime.getRuntime();
    try {
        Process process = runtime.exec(cmd);
        process.waitFor();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

I would like to include the R script "hierarchicalClusteringScript.R" into the jar file. In case I do is there a way to call the script from code? Which path should I use?

Thanks a lot in advance


Solution

  • In order to extract the script from your JAR, normally we seldom perform a JAR/ZIP extract. When you put the script in the JAR, it usually implies that it is in your classpath. Therefore, just locate it as a resource, get the inputStream to it, and read the resources and write it to a temp directory. These few steps should be easy enough that you can easily find code sample from the net easily.

    some hints for you:

    Class#getResourceAsStream()
    FileOutputStream
    File#createTempFile()