[java] Compiling and Running Java Code in Sublime Text 2

I am trying to compile and run Java code in Sublime Text 2. Don't just tell me to do it manually in the Command Prompt. Can anyone tell me how?

Btw, I am on Windows 7...

This question is related to java compilation sublimetext2

The answer is


This is code to compile and run java in sublime text 3

"shell_cmd": "javac -d . $file && java ${file_base_name}.${file_base_name}", "shell": true


Refer the solution at: http://www.compilr.org/compile-and-run-java-programs/

Hope that solves, for both compiling and running the classes within sublime..... You can see my script in the comments section to try it out in case of mac...

EDIT: Unfortunately, the above link is broken now. It detailed all the steps required for comiling and running java within sublime text. Anyways, for mac or linux systems, the below should work:

modify javac.sublime-build file to:


#!/bin/sh

classesDir="/Users/$USER/Desktop/java/classes/"
codeDir="/Users/$USER/Desktop/java/code/"
[ -f "$classesDir/$1.class" ] && rm $classesDir/$1.class
for file in $1.java
do
echo "Compiling $file........"
javac -d $classesDir $codeDir/$file
done
if [ -f "$classesDir/$1.class" ]
then
echo "-----------OUTPUT-----------"
java -cp $classesDir $1
else
echo " "
fi

Here, I have made a folder named "java" on the Desktop and subfolders "classes" and "code" for maintaining the .class and .java files respectively, you can modify in your own way.


So this is what i added to the JavaC.sublime-build file

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

    "variants": [

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

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

What this does is that it creates variants to the regular build command (ctrl+b). With ctrl+b you will still be able to compile your code. If you do shift+ctrl+b the first variant will be executed, which in this case is javac with the -Xlint option. The second and final variant is the java command itself. you can place this as your first variant and shift+ctrl+b will actually execute the java code.

Also, notice that each variant as a "name". This basically allows this specific "build" option to show up in the shift+ctrl+p option. So using this configuration, you can simply do shift+ctrl+p and type "Run Java" and hit enter, and your code will execute.

Hope this helped.


The Build System JavaC works like a charm but fails when you want to give input from stdin in Sublime-text. But you can edit the build system to make it receive input from user. This is the modified JavaC build I'm using on Ubuntu 18.04 LTS. You can edit the build System or create a new build system.

To Create a new build system.

  • Go to Tools>>Build System>>New Build System.
  • Copy Paste the Below code and File>>Save.

    {

    "shell_cmd": "javac \"$file\"",
    "file_regex": "^(...*?):([0-9]*):?([0-9]*)",
    "selector": "source.java",
    "variants": 
    [
        {
            "shell_cmd":"bash -c \"javac $file\" && gnome-terminal -- bash -c \"java $file_base_name ;read\"", 
            "name": "Run"
        }
    
    ]    
    

    }

To Edit the existing Java C build file


compile and running as per documentation of sublime text 2 nd 3

step- 1: set environment variables for java as u know already or refer somewhere

strp-2: open new document and copy paste code below

{
"cmd": ["javac", "$file_name", "&&", "java", "$file_base_name"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.java",
"shell":true }

step-3: save the document as userjavaC.sublime-build in directory C:\Users\myLapi\AppData\Roaming\Sublime Text 3\Packages\User

step-4:

after done select as tools->build systems->userjavaC

to both compile and run press ctrl+b


{
"shell_cmd": "javac -Xlint  \"${file}\"",
"file_regex": "^(...*?):([0-9]*):?([0-9]*)",
"working_dir": "${file_path}",
"selector": "source.java",

"variants": [

    { "shell_cmd":"javac -Xlint  \"${file}\" && java $file_base_name  < input.txt > output.txt",
      "name": "Run"
    }
   ]
}

save this sublime build and run the program with ctrl + shift + B with run variant.Without run variant it will just create .class file but wont run it.

This build will read the input from input.txt and print the output in output.txt.

Note: both input.txt and output.txt must be present in the same working directory as your .java file.


For Sublime Text 3
in "C:\Program Files\Sublime Text 3\Packages" you get java.sublime-package copy it to another folder change its extension from .sublime-package to zip and extract it you get JavaC.sublime-build file for your Modifications as above.
after all modifications extracted java folder again convert to .zip and change its extension .zip to .sublime-package. after that copy and paste this file to C:\Program Files\Sublime Text 3\Packages.
this will help you!

(even you get my file from http://upfile.mobi/363820 or http://www.4shared.com/file/73SkzY-Kba/Java.html link I use to run java code i use trick of "Wesley Baugh" so you need to copy runJava.bat file to your C:\Program Files (x86)\Java\jdk1.8.0\bin directory as he says. and copy above linked file to C:\Program Files\Sublime Text 3\Packages)


Sublime Text 3 has a slightly different solution. This is a modification of vijay's answer, which I was using before.

 {
     "shell_cmd": "javac -Xlint \"${file}\"",
     "file_regex": "^(...*?):([0-9]*):?([0-9]*)",
     "working_dir": "${file_path}",
     "selector": "source.java",

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

Paste the above into a new file called JavaC.sublime-buildand put it into your User packages. This can be found in C:\Users\You\AppData\Roaming\Sublime Text 3\Packages\User.

Ctrl-B will compile. Ctrl-Shift-B will run.


This version of JavaC.sublime-build which is edited from vijay's answer works for me on both Windows 7 and Mac for Sublime Text 3.

I edited it so Ctrl+b or command+b is sufficient for both build + run.

{
"shell_cmd": "javac -Xlint $file && java $file_base_name",
"file_regex": "^(...*?):([0-9]*):?([0-9]*)",
"selector": "source.java",
"shell": true
}

'&&' ensures that the second part runs only when first part succeeds ie only when the class file is generated. You can find more related info here: http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/ntcmds_shelloverview.mspx?mfr=true


I am using Windows 7. The below solution works for me!!

**Open** the file JavaC.sublime-build and replace all the code in the file with the code below:

{
 "cmd": ["javac", "$file_name","&&","java", "$file_base_name"],
 "file_regex": "^(...*?):([0-9]*):?([0-9]*)",
 **"path": "C:\\Program Files\\Java\\jdk1.6.0\\bin\\",**
 "selector": "source.java",
 "shell": true
 }

Remember to replace "C:\Program Files\Java\jdk1.6.0\bin\" with the path where you put your jdk. And make sure to add the path of you java JDK to the environment variable "PATH". Refer to bunnyDrug's post to set up the environment variable. Best!!


I followed a post in this thread and got it working perfectly:

Make the bat file with the following, and save it anywhere in your PATH. I suggest C:\Program Files\Java\jdk*\bin\ to keep everything together.

@ECHO OFF
cd %~dp1
javac %~nx1
java %~n1

then edit C:\Users\your_user_name\AppData\Roaming\Sublime Text 2\Packages\Java\JavaC.sublime-build, the contents will be

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

replace "javac" with the name of your bat file (for instance, javacexec.bat) and save it.


I find the method in the post Compile and Run Java programs with Sublime Text 2 works well and is a little more convenient than the other methods. Here is a link to the archived page.

For Windows:

Step 1:

Create runJava.bat with the following code.

@ECHO OFF
cd %~dp1
ECHO Compiling %~nx1.......
IF EXIST %~n1.class (
DEL %~n1.class
)
javac %~nx1
IF EXIST %~n1.class (
ECHO -----------OUTPUT-----------
java %~n1
)

Copy this file to jdk bin directory.

Step 2:

  1. Open Sublime package directory using Preferences > Browse Packages..
  2. Go to Java Folder
  3. Open JavaC.sublime-build and replace line
    "cmd": ["javac", "$file"],
    with
    "cmd": ["runJava.bat", "$file"],

Done!

Write programs and Run using CTRL + B

Note: Instructions are different for Sublime 3.


This is how I did it with these easy steps:

Setup a new build system:

  1. Tools > Build System > New Build System

  2. Replace the default code with the following:

    {
       "cmd": ["javac","$file_name","&&","java","$file_base_name"], 
       "path": "C:\\Program Files\\Java\\jdk1.7.0_25\\bin\\", 
       "shell": true
    }
    // locate the path of your jdk installation and replace it with 'path' 
    
  3. Save the file by giving it a name (I named mine "Java")

Activate the build system:

  1. Tools > Build System > Java (name of the file you saved it with)
  2. Now run your program with Ctrl + B

This is mine using sublime text 3. I needed the option to open the command prompt in a new window. Java compile is used with the -Xlint option to turn on full messages for warnings in Java.

I have saved the file in my user package folder as Java(Build).sublime-build

{
     "shell_cmd": "javac -Xlint \"${file}\"",
     "file_regex": "^(...*?):([0-9]*):?([0-9]*)",
     "working_dir": "${file_path}",
     "selector": "source.java",
     "variants":
     [
          {
               "name": "Run",
                "shell_cmd": "java \"${file_base_name}\"",
          },
          {
               "name": "Run (External CMD Window)",
               "shell_cmd": "start cmd /k java \"${file_base_name}\""
          }
     ]
}

You can compile and run your code entirely in ST, and it's very quick/simple. There's a recent ST package called Javatar that can do this. https://javatar.readthedocs.org


Make sure u install JDK/JRE first.

If you are mac user than follow this steps:

open terminal go to your root dictionary by typing

cd ..

repeatedly. use

ls

to see if u have reach the root

you will see Library folder Now follow this path Library/Java/JVM/bin Once you get into bin you can see JavaC file

Now u need to get the path of this folder for that just write this command

pwd

Copy paste it to your sublime JavaC file and build java code in sublime by cmd+b.


Alex Yao's Answer is the simplest solution, if you just want to build and run Java program w/o taking any input from the console use the solution provided by Alex Yao. However if you would like to take input from the console then refer to the following link

Java console input in Sublime Text 2?


By following the steps below, you will have 2 Build Systems in sublime - "JavaC" and "JavaC_Input".

"JavaC" would let you run code that doesn't require user input and display the results in sublime's terminal simulator, which is convenient and nice-looking. "JavaC_Input" lets you run code that requires user input in a separate terminal window, it's able to accept user input. You can also run non-input-requiring code in this build system, so if you don't mind the pop-up, you can just stick with this build system and don't switch. You switch between build systems from Tools -> Build System. And you compile&run code using ctrl+b.

Here are the steps to achieve this:

(note: Make sure you already have the basic setup of the java system: install JDK and set up correct CLASSPATH and PATH, I won't elaborate on this)

"JavaC" build system setup

1, Make a bat file with the following code, and save it under C:\Program Files\Java\jdk*\bin\ to keep everything together. Name the file "javacexec.bat".

@ECHO OFF
cd %~dp1
javac %~nx1
java %~n1

2, Then edit C:\Users\your_user_name\AppData\Roaming\Sublime Text 2\Packages\Java\JavaC.sublime-build (if there isn't any, create one), the contents will be

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

"JavaC_Input" build system setup

1, Install Cygwin [http://www.cygwin.com/]

2, Go to C:\Users\your_user_name\AppData\Roaming\Sublime Text 2\Packages\Java\, then create a file called "JavaC_Input.sublime-build" with the following content

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

3, Make a bat file with the following code, and save it under C:\Program Files\Java\jdk*\bin\ to keep everything together. Name the file "javacexec_input.bat".

@echo off
javac  -Xlint:unchecked %~n1.java 
start cmd /k java -ea %~n1

As detailed here:

http://sublimetext.userecho.com/topic/90531-default-java-build-system-update/

Steps I took to remedy this

  1. Click Start

  2. Right click on 'Computer'

2.5 Click Properties.

  1. On the left hand side select 'Advanced System Settings'

  2. Near the bottom click on 'Environment Variables'

  3. Scroll down on 'System Variables' until you find 'PATH' - click edit with this selected.

  4. Add the path to your Java bin folder. Mine ends up looking like this:

    CODE: SELECT ALL

    ;C:\Program Files\Java\jdk1.7.0_03\bin\


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to compilation

WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()' How to enable C++17 compiling in Visual Studio? How can I use/create dynamic template to compile dynamic Component with Angular 2.0? Microsoft Visual C++ Compiler for Python 3.4 C compile : collect2: error: ld returned 1 exit status Error:java: invalid source release: 8 in Intellij. What does it mean? Eclipse won't compile/run java file IntelliJ IDEA 13 uses Java 1.5 despite setting to 1.7 OPTION (RECOMPILE) is Always Faster; Why? (.text+0x20): undefined reference to `main' and undefined reference to function

Examples related to sublimetext2

Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? How to Install Sublime Text 3 using Homebrew 80-characters / right margin line in Sublime Text 3 Comparing the contents of two files in Sublime Text What is the default font of Sublime Text? Showing the same file in both columns of a Sublime Text window What is the difference between Sublime text and Github's Atom Sublime Text 2 multiple line edit Set Encoding of File to UTF8 With BOM in Sublime Text 3 Regex replace uppercase with lowercase letters