Search code examples
javabuildsublimetext2javac

Is it possible to build/run java with libraries using Sublime Text 2


I am able to build java programs in Sublime Text 2 using the build script. However, is it possible to modify the script to include referenced libraries in the build automatically, say in a folder lib\.

{
"cmd": ["javac", "-Xlint", "$file"],
"file_regex": "^(...*?):([0-9]*):?([0-9]*)",
"selector": "source.java",

"variants": [
    { "cmd": ["java", "$file_base_name"],
      "name": "Run"
    }
]
}

Thanks

Edit: I am now able to build and run from Sublime Text using

{
"cmd": ["javac", "-cp", "*;.", "-Xlint", "$file"],
"file_regex": "^(...*?):([0-9]*):?([0-9]*)",
"selector": "source.java",

"variants": [

    { "cmd": ["java", "-cp", "*;.", "$file_base_name"],
      "name": "Run"
    }
] }

Solution

  • Create an external script file (e.g. java-build) and reference it from JavaC.sublime-text:

      "cmd": ["java-build", "$file", "$file_path"],       
    

    If the lib folder is located next to the java file being compiled, the script may look like this:

    java-build.bat (for Windows):

    @echo off
    cd %2
    javac -cp "*;." -Xlint %1 %2\lib\*.java
    

    java-build.sh (for Unix):

    #!/bin/bash
    cd $2
    javac -cp ./*:. -Xlint $1 $2/lib/*.java
    

    If you want your .class files to be put in a separate place add -d path argument to javac. It is also a good idea to delete old classes before compiling to make sure you won't use different versions if compiler breaks on some file: -rm *.class (del *.class for windows).

    This discussion may help: Compiling and Running Java Code in Sublime Text 2