简体   繁体   中英

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

Your path might not appear to work if you haven't referenced the correct folder - that set by step I posted way back only applied for that version of the JDK.

If you aren't seeing any menu when you right click on 'Computer' try this instead.

For JDK version jdk1.7.0_07 Just update this with location of your JDK when a new version is released.

  • Click START
  • Type "Path" (without the quotes) into the search area
  • You should see "Edit environment variables for your account" <--- click this
  • A window should appear titled "Environment Variables"
    • Click TEMP on the top area
    • Scroll a little bit on the bottom second area until you find Path
    • Select Path and click Edit...
  • Paste this in at the very end of bottom text area

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

  • Make sure to OK out of both windows
  • Restart Sublime text if needed

That's all there is to it.

So to actually get compiling and running your Java programs after completing the above, you will need to do the following. Just create a simple java class so you are on the same page as me

Building your Java class

  • Open a new SublimeText2 document and paste the following

     class hello { public static void main(String[] args) { System.out.println("Hello World!"); } } 
  • Then save that file to your Desktop - call it

     hello.java 
  • you should have something like this Java和保存的文件

  • Now press Ctrl+b on your keyboard to build your java class which should produce this! 建立结果

Finally! - Running your Java program!

  • You need to open a command prompt window, so go ahead and do that.
  • Then navigate to the folder (in this case our desktop) where your java class is located
  • navigating using the command prompt is easy - just use

     cd <-- this stands for change directory dir <-- this will list everything in the current directory if you get stuck! 
  • in my case it looks like this

dir和cd的例子

  • Cool, looks like we are in the right place.
  • Finally type the following

     java hello 

java你好结果

I hope this helps anyone who stumbles across this!

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.

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.

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-build and 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

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

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

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.

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

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)

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

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

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.

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

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?

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}\""
          }
     ]
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM