80

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...

tshepang
  • 12,111
  • 21
  • 91
  • 136
tolluy
  • 919
  • 1
  • 7
  • 4
  • 4
    Sublime forums seem to have answers for this: http://www.sublimetext.com/forum/viewtopic.php?f=3&t=4805, http://sublimetext.userecho.com/topic/90531-default-java-build-system-update/ – madth3 May 12 '12 at 01:23
  • i have already tried those... i get this: [Error 2] The system cannot find the file specified [Finished] – tolluy May 12 '12 at 01:25
  • 2
    That problem is solved in the posts in the forum. You need to add java and javac to your PATH, I think. – madth3 May 12 '12 at 01:27
  • In my case where I was only trying to build and run a single java file within Sublime Text 3 beta in Windows 7 using a single command Ctrl+B, putting the following under "\Packages\Java\JavaC.sublime-build" file (created folder/file that didn't exist) worked. Change your Java bin directory as needed. { "cmd": ["javac", "$file_name", "&&", "java", "$file_base_name"], "shell": true, "path": "C:\\Program Files (x86)\\Java\\jdk1.8.0_05\\bin", "file_regex": "^(...*?):([0-9]*):?([0-9]*)", "selector": "source.java" } – Lal Jul 30 '14 at 21:28
  • 1
    For the record, none of the answers below seem to support anything more complicated than a basic hello-world type of program. Any program that has external imports and requires setting the `CLASSPATH` and/or passing the `cp` switch for the project will not work. You would either need to modify the build-system each time you want to work on a different project, or find some other solution (only a masochistic sociopath would modify the `CLASSPATH` variable at the OS level each time). – Synetech Mar 24 '16 at 23:03
  • 1
    I wrote a sublime plugin that does exactly the same thing. I made it for Sublime Text 3, not sure if it will work for Sublime Text 2. This plugin lets you compile and run your java program without any need of command prompt. The only requirement is that JAVA_HOME should be set on your operating system. See this git repo for more info about this plugin. https://github.com/jainrish/sublime-plugins/tree/master/RunProgram – jainrish Feb 21 '17 at 19:14
  • Using the following url to github you can download JPack. Use JPack to run java in Sublime Text. JPack is really easy to use and all the information you need is on that page. The page says Install but you don't need to install it. Just to add the path to the file. JPack: https://github.com/dannyvantol/jpack – Danny van Tol Mar 06 '16 at 18:08

19 Answers19

77

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.

Hulk1991
  • 3,079
  • 13
  • 31
  • 46
vijay
  • 2,646
  • 2
  • 23
  • 37
  • 10
    If you want to use ctrl+shift+b to run, change "name" field to "Run". – mtyurt Nov 16 '13 at 21:39
  • 4
    This has Changed for ST3: * replace "cmd" with shell_cmd * remove the squre braces * put the whole command in a string – Dagoth Ulen Apr 11 '14 at 20:15
  • 1
    +1 As the [ST build-system docs](http://docs.sublimetext.info/en/latest/reference/build_systems/basics.html#overview) say, the build commands don’t necessarily have to compile a file, they can run anything, including the compiled program. Thus, *this* answer is the correct way to compile *and run* Java from ST(2) without using the command-prompt. (In fact, TextPad has a similar ability to define and run arbitrary programs, and has a built-in support for Java to allow you to bind one hotkey to compile and another to run.) – Synetech Mar 24 '16 at 22:59
  • thanks for this worked. and thanks @mtyurt, changed `Run Java` to `Run` and now pressing `ctrl+shift+b` executing program. – Nishant Bhakta Feb 20 '17 at 12:53
  • And where can one find `*.sublime-build` file? – YetAnotherBot Mar 06 '19 at 07:01
19

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.

Community
  • 1
  • 1
vancexu
  • 1,548
  • 3
  • 19
  • 30
17

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.

Rokit
  • 977
  • 13
  • 23
  • 3
    Nice job. This works on Linux, too, although I didn't seem to need the extra double-quotes and leading escape symbol. =:). But it works. Thanks. – NYCeyes Aug 11 '15 at 21:36
8

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

Alex Yao
  • 91
  • 1
  • 4
  • 1
    This solution works for sublime text 2 too if replacing the `shell_cmd` with `cmd`. This is the only solution that worked for me. Thank you. – Andritchi Alexei Jan 16 '16 at 09:55
7

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

saroj
  • 81
  • 1
  • 3
6

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

Sam003
  • 540
  • 6
  • 17
3

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.

Bhavesh Agarwal
  • 603
  • 2
  • 6
  • 13
2

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\

jgritty
  • 11,660
  • 3
  • 38
  • 60
  • this doesnt work, i click start, right click Computer and i dont get anything, just a single menu, not double... and i was following thenewbostons tutorials, so i already did the PATH stuff – tolluy May 12 '12 at 01:44
2

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)

2

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

Keng
  • 854
  • 10
  • 10
2

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

1

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.

Ascendant
  • 2,430
  • 3
  • 26
  • 34
1

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
1
{
"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.

akhil
  • 41
  • 3
0

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.

0

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?

0

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}\""
          }
     ]
}
scopchanov
  • 7,966
  • 10
  • 40
  • 68
moyarich
  • 31
  • 8
0

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

Raghav
  • 1
  • 3
0

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
Ahtisham
  • 9,170
  • 4
  • 43
  • 57