I used to write and run python code in sublime, but now I want to learn Java so I want to know how to run Java code in sublime.
I read some solutions online but they didn't completely make sense.
I sort of get that I first need to create a .sh file that includes the following code:
#ECHO OFF
javac %1.java
if errorlevel 1 goto error
echo [OK, running... ]
java %1
goto end
:error
echo [Compile was unsuccessful]
goto end
:end
But I'm confused where should I save the above file? In the sublime folder?
And then I need to create another file .java that includes:
{
"cmd": ["javacr.bat", "$file_base_name" ],
"file_regex": "^(...*?):([0-9]*):?([0-9]*)",
"working_dir": "${file_path}",
"selector": "source.java"
}
But I also need to save this file somewhere and I don't know what is Java.sublime-build as they said? And what is the PATH?
I really appreciate if someone could explain to me step by step how to achieve these. Thanks!
Add JDK to your path.
Save your MyProg.java somewhere.
Execute javac myProg.java to compile to bytcode.
Then java myProg to run the actual program.
Alternatively download a decent ide (intellij or Netbeans) it will help greatly.
Steps to use java in sublime:
First Install JDK
In sublime go to Tools -> Build System -> New Build System
put below code:
{
"cmd": ["javac", "$file_name", "&&", "java" ,"$file_base_name"],
"selector": "source.java",
"file_regex": "^\\s*File \"(...*?)\", line ([0-9]*)", "path" :
"C:\\Program Files\\Java\\jdk-14.0.2\\bin\\",
"shell":true
}
Save it with any name (like, Runjava.sublime-build)
Note: In path give whatever java version present in your system at these location "C:\Program Files\Java\jdk-14.0.2\bin\"
Then, create a folder with three files in it B.java(Main java file), input.txt, output.txt.
Go to Tools -> Build System -> Select Runjava
put below code in B.java file:
import java.io.*;
import java.util.*;
public class B {
public static void main(String[] args) {
try {
System.setIn(new FileInputStream("input.txt"));
System.setOut(new PrintStream(new FileOutputStream("output.txt")));
} catch (Exception e) {
System.err.println("Error");
}
System.out.println("Hello World!");
}
}
give input in input.txt file
see output in ouput.txt file
After correctly Installing Java on your machine (setting the JDK's path).
-Write you java program then save it where ever you want.
-Compile your program with javac command(in terminal), this will generate a .class file if your compilation went without errors(javac name_of_your_program.java).
-Run the generated file with the "java" command and that's all you need.
PATH is an environment variable, it will contain the path to your JDK to tell your system where to find the appropriate Java command.
.
My advice is simply to work with an IDE (there are many of them), It's much more simple and provide you with many tools.
Related
I am using VSCode with Maven to learn Java(my javac -version is 11.0.10) under macOS Big Sur.
It is ok when I run the code in the terminal by using "RUN," which show on the list of VSCode. However, it always shows the error "Could Not Find Or Load Main Class"(actually in Chinese "找不到或無法載入主要類別 hello") and the reason "java.lang.NoClassDefFoundError: org/seifert/learnjava8/hello (wrong name: hello)".
As you can see, the .java file is just a straightforward one to show"hello world."
the whole screen image here
Had anyone who uses Code Runner met this problem before? How can I resolve this?
The error is because of it isn't called by its "fully qualified name". The project has to be called as hello.java rather than simply hello. The execution command for your file should be:
java <directory in which your file lies> hello.java
So your error should have looked like this:
The error is shown in this picture.
And if you use .java then, the problem can be solved as:
The solved program is in this picture
As you mentioned you use code runner. Follow the steps:
Head over to the setting of your vscode and search for code runner and find
Coderunner: Executor Map
Click on "Edit in settings.json"
Settings page.
Look for java as: java in settings.json page
"code-runner.executorMap": {
"java": "cd $dir && javac $fileName && java $fileNameWithoutExt",
}
Just add .java at the end of the line inside the Double quotes WITHOUT ANY SPACE. Then, save it.
"code-runner.executorMap": {
"java": "cd $dir && javac $fileName && java $fileNameWithoutExt.java",
}
Now run your program. You are good to go!
The error occurs because it must be called with its fully qualified name. To be clear, the name of this class is not hello, It's org.seifert.learnjava8.hello. I create a simple maven project, so the right execution command is:
Turn to the folder java: cd src\main\java
Compile the .java file: javac org\seifert\learnjava8\hello.java
Run the java file: java org.seifert.learnjava8.hello
When it comes to run the java file by Code Runner, the execution commands is
"code-runner.executorMap":{
"java": "cd $dir && javac $fileName && java $fileNameWithoutExt",
}
The $dir represents the direct path to current opened file, and the javac and java command doesn't include the package to be compiled together, then caused the error:
So the solution is turning to the settings and edit the "code-runner.executorMap":
"code-runner.executorMap":{
"java": "cd /users/seiferthan/.../src/main/java && javac org/seifert/learnjava8/$fileName && java org.seifert.learnjava8.$fileNameWithoutExt",
}
I'm trying to execute a Java program from the command line in Windows. Here is my code:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class CopyFile
{
public static void main(String[] args)
{
InputStream inStream = null;
OutputStream outStream = null;
try
{
File afile = new File("input.txt");
File bfile = new File("inputCopy.txt");
inStream = new FileInputStream(afile);
outStream = new FileOutputStream(bfile);
byte[] buffer = new byte[1024];
int length;
// copy the file content in bytes
while ((length = inStream.read(buffer)) > 0)
{
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.close();
System.out.println("File is copied successful!");
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
I'm not sure how to execute the program - any help? Is this possible on Windows? Why is it different than another environment (I thought JVM was write once, run anywhere)?
Source: javaindos.
Let's say your file is in C:\mywork\
Run Command Prompt
C:\> cd \mywork
This makes C:\mywork the current directory.
C:\mywork> dir
This displays the directory contents. You should see
filenamehere.java among the files.
C:\mywork> set path=%path%;C:\Program Files\Java\jdk1.5.0_09\bin
This tells the system where to find JDK programs.
C:\mywork> javac filenamehere.java
This runs javac.exe, the compiler. You should see nothing but the
next system prompt...
C:\mywork> dir
javac has created the filenamehere.class file. You should see
filenamehere.java and filenamehere.class among the files.
C:\mywork> java filenamehere
This runs the Java interpreter. You should then see your program
output.
If the system cannot find javac, check the set path command. If javac
runs but you get errors, check your Java text. If the program
compiles but you get an exception, check the spelling and
capitalization in the file name and the class name and the java
HelloWorld command. Java is case-sensitive!
To complete the answer :
The Java File
TheJavaFile.java
Compile the Java File to a *.class file
javac TheJavaFile.java
This will create a TheJavaFile.class file
Execution of the Java File
java TheJavaFile
Creation of an executable *.jar file
You've got two options here -
With an external manifest file :
Create the manifest file say - MANIFEST.mf
The MANIFEST file is nothing but an explicit entry of the Main Class
jar -cvfm TheJavaFile.jar MANIFEST.mf TheJavaFile.class
Executable by Entry Point:
jar -cvfe TheJavaFile.jar <MainClass> TheJavaFile.class
To run the Jar File
java -jar TheJavaFile.jar
Complile a Java file to generate a class:
javac filename.java
Execute the generated class:
java filename
In case your Java class is in some package. Suppose your Java class named ABC.java is present in com.hello.programs, then you need to run it with the package name.
Compile it in the usual way:
C:\SimpleJavaProject\src\com\hello\programs > javac ABC.java
But to run it, you need to give the package name and then your java class name:
C:\SimpleJavaProject\src > java com.hello.programs.ABC
Since Java 11, java command line tool has been able to run a single-file source-code directly. e.g.
java HelloWorld.java
This was an enhancement with JEP 330: https://openjdk.java.net/jeps/330
For the details of the usage and the limitations, see the manual of your Java implementation such as one provided by Oracle: https://docs.oracle.com/en/java/javase/11/tools/java.html
Assuming the file is called "CopyFile.java", do the following:
javac CopyFile.java
java -cp . CopyFile
The first line compiles the source code into executable byte code. The second line executes it, first adding the current directory to the class path (just in case).
It is easy. If you have saved your file as A.text first thing you should do is save it as A.java. Now it is a Java file.
Now you need to open cmd and set path to you A.java file before compile it. you can refer this for that.
Then you can compile your file using command
javac A.java
Then run it using
java A
So that is how you compile and run a java program in cmd.
You can also go through these material that is Java in depth lessons. Lot of things you need to understand in Java is covered there for beginners.
You can compile any java source using javac in command line ; eg, javac CopyFile.java.
To run : java CopyFile.
You can also compile all java files using javac *.java as long as they're in the same directory
If you're having an issue resulting with "could not find or load main class" you may not have
jre in your path. Have a look at this question:
Could not find or load main class
On Windows 7 I had to do the following:
quick way
Install JDK http://www.oracle.com/technetwork/java/javase/downloads
in windows, browse into "C:\Program Files\Java\jdk1.8.0_91\bin" (or wherever the latest version of JDK is installed), hold down shift and right click on a blank area within the window and do "open command window here" and this will give you a command line and access to all the BIN tools. "javac" is not by default in the windows system PATH environment variable.
Follow comments above about how to compile the file ("javac MyFile.java" then "java MyFile") https://stackoverflow.com/a/33149828/194872
long way
Install JDK http://www.oracle.com/technetwork/java/javase/downloads/index.html
After installing, in edits the Windows PATH environment variable and adds the following to the path C:\ProgramData\Oracle\Java\javapath. Within this folder are symbolic links to a handful of java executables but "javac" is NOT one of them so when trying to run "javac" from Windows command line it throws an error.
I edited the path: Control Panel -> System -> Advanced tab -> "Environment Variables..." button -> scroll down to "Path", highlight and edit -> replaced the "C:\ProgramData\Oracle\Java\javapath" with a direct path to the java BIN folder "C:\Program Files\Java\jdk1.8.0_91\bin".
This likely breaks when you upgrade your JDK installation but you have access to all the command line tools now.
Follow comments above about how to compile the file ("javac MyFile.java" then "java MyFile") https://stackoverflow.com/a/33149828/194872
STEP 1: FIRST OPEN THE COMMAND PROMPT WHERE YOUR FILE IS LOCATED. (right click while pressing shift)
STEP 2: THEN USE THE FOLLOWING COMMANDS TO EXECUTE.
(lets say the file and class name to be executed is named as Student.java)The example program is in the picture background.
javac Student.java
java Student
As of Java 9, the JDK includes jshell, a Java REPL.
Assuming the JDK 9+ bin directory is correctly added to your path, you will be able to simply:
Run jshell File.java — File.java being your file of course.
A prompt will open, allowing you to call the main method: jshell> File.main(null).
To close the prompt and end the JVM session, use /exit
Full documentation for JShell can be found here.
Now (with JDK 9 onwards), you can just use java to get that executed.
In order to execute "Hello.java" containing the main, one can use:
java Hello.java
You do not need to compile using separately using javac anymore.
You can actually run Java program as you would shell or python scripts without manually compile the Java file, as described in
JEP 330. That is available since JDK 11.
If you create a file testing, and put the following you should be able to run it as command testing. You need to make it executable in Linux and Mac OSX with chmod +x testing.
#!/usr/bin/env java --source 11
public class Test {
public static void main(String [] args) {
System.out.println("Hello world!");
System.exit(0);
}
}
You are not allowed to use the file extension .java in the previous example.
$ chmod +x testing
$ ./testing
Hello world!
$
But you can still execute if it is was name Test.java without the shebang "#!" prefix like this:
public class Test {
public static void main(String [] args) {
System.out.println("Hello again!");
System.exit(0);
}
}
Then execute the file Test.java with following command:
$ java Test.java
Hello again!
$
So this works as long as you have a new enough Java compiler in the path, check with java -version. More information in this blog.
I have source code for QR code generation using Java.
I don't know how to run Java in command prompt.
two jar files
E:\QR Code\lib\core-2.2.jar
E:\QR Code\lib\javase-2.2.jar
Java code path
E:\QR Code\src\com\javapapers\java\QRCode.java
Source code
http://javapapers.com/core-java/java-qr-code
Explain me how to run the java in command prompt
Regards
Karthikeyan K
To make sure that Windows can find the Java compiler and interpreter:
Select Start -> Computer -> System Properties -> Advanced system settings Environment Variables -> System variables -> PATH. ...
Prepend C:\Program Files\Java\jdk1.6.0_27\bin; to the beginning of the PATH variable.
Click OK
Then open command prompt and check if Java path setup done by below command
java -version
If everything ok it will show you which Java version you have installed .
then you can run java program Like below a example
C:\test> javac HelloWorld.java
I have test folder and it have HelloWorld.java file inside it after this
C:\test> java HelloWorld
It will give you output in my file i have added below content
public class HelloWorld{
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
I'm trying to execute a Java program from the command line in Windows. Here is my code:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class CopyFile
{
public static void main(String[] args)
{
InputStream inStream = null;
OutputStream outStream = null;
try
{
File afile = new File("input.txt");
File bfile = new File("inputCopy.txt");
inStream = new FileInputStream(afile);
outStream = new FileOutputStream(bfile);
byte[] buffer = new byte[1024];
int length;
// copy the file content in bytes
while ((length = inStream.read(buffer)) > 0)
{
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.close();
System.out.println("File is copied successful!");
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
I'm not sure how to execute the program - any help? Is this possible on Windows? Why is it different than another environment (I thought JVM was write once, run anywhere)?
Source: javaindos.
Let's say your file is in C:\mywork\
Run Command Prompt
C:\> cd \mywork
This makes C:\mywork the current directory.
C:\mywork> dir
This displays the directory contents. You should see
filenamehere.java among the files.
C:\mywork> set path=%path%;C:\Program Files\Java\jdk1.5.0_09\bin
This tells the system where to find JDK programs.
C:\mywork> javac filenamehere.java
This runs javac.exe, the compiler. You should see nothing but the
next system prompt...
C:\mywork> dir
javac has created the filenamehere.class file. You should see
filenamehere.java and filenamehere.class among the files.
C:\mywork> java filenamehere
This runs the Java interpreter. You should then see your program
output.
If the system cannot find javac, check the set path command. If javac
runs but you get errors, check your Java text. If the program
compiles but you get an exception, check the spelling and
capitalization in the file name and the class name and the java
HelloWorld command. Java is case-sensitive!
To complete the answer :
The Java File
TheJavaFile.java
Compile the Java File to a *.class file
javac TheJavaFile.java
This will create a TheJavaFile.class file
Execution of the Java File
java TheJavaFile
Creation of an executable *.jar file
You've got two options here -
With an external manifest file :
Create the manifest file say - MANIFEST.mf
The MANIFEST file is nothing but an explicit entry of the Main Class
jar -cvfm TheJavaFile.jar MANIFEST.mf TheJavaFile.class
Executable by Entry Point:
jar -cvfe TheJavaFile.jar <MainClass> TheJavaFile.class
To run the Jar File
java -jar TheJavaFile.jar
Complile a Java file to generate a class:
javac filename.java
Execute the generated class:
java filename
In case your Java class is in some package. Suppose your Java class named ABC.java is present in com.hello.programs, then you need to run it with the package name.
Compile it in the usual way:
C:\SimpleJavaProject\src\com\hello\programs > javac ABC.java
But to run it, you need to give the package name and then your java class name:
C:\SimpleJavaProject\src > java com.hello.programs.ABC
Since Java 11, java command line tool has been able to run a single-file source-code directly. e.g.
java HelloWorld.java
This was an enhancement with JEP 330: https://openjdk.java.net/jeps/330
For the details of the usage and the limitations, see the manual of your Java implementation such as one provided by Oracle: https://docs.oracle.com/en/java/javase/11/tools/java.html
Assuming the file is called "CopyFile.java", do the following:
javac CopyFile.java
java -cp . CopyFile
The first line compiles the source code into executable byte code. The second line executes it, first adding the current directory to the class path (just in case).
It is easy. If you have saved your file as A.text first thing you should do is save it as A.java. Now it is a Java file.
Now you need to open cmd and set path to you A.java file before compile it. you can refer this for that.
Then you can compile your file using command
javac A.java
Then run it using
java A
So that is how you compile and run a java program in cmd.
You can also go through these material that is Java in depth lessons. Lot of things you need to understand in Java is covered there for beginners.
You can compile any java source using javac in command line ; eg, javac CopyFile.java.
To run : java CopyFile.
You can also compile all java files using javac *.java as long as they're in the same directory
If you're having an issue resulting with "could not find or load main class" you may not have
jre in your path. Have a look at this question:
Could not find or load main class
On Windows 7 I had to do the following:
quick way
Install JDK http://www.oracle.com/technetwork/java/javase/downloads
in windows, browse into "C:\Program Files\Java\jdk1.8.0_91\bin" (or wherever the latest version of JDK is installed), hold down shift and right click on a blank area within the window and do "open command window here" and this will give you a command line and access to all the BIN tools. "javac" is not by default in the windows system PATH environment variable.
Follow comments above about how to compile the file ("javac MyFile.java" then "java MyFile") https://stackoverflow.com/a/33149828/194872
long way
Install JDK http://www.oracle.com/technetwork/java/javase/downloads/index.html
After installing, in edits the Windows PATH environment variable and adds the following to the path C:\ProgramData\Oracle\Java\javapath. Within this folder are symbolic links to a handful of java executables but "javac" is NOT one of them so when trying to run "javac" from Windows command line it throws an error.
I edited the path: Control Panel -> System -> Advanced tab -> "Environment Variables..." button -> scroll down to "Path", highlight and edit -> replaced the "C:\ProgramData\Oracle\Java\javapath" with a direct path to the java BIN folder "C:\Program Files\Java\jdk1.8.0_91\bin".
This likely breaks when you upgrade your JDK installation but you have access to all the command line tools now.
Follow comments above about how to compile the file ("javac MyFile.java" then "java MyFile") https://stackoverflow.com/a/33149828/194872
STEP 1: FIRST OPEN THE COMMAND PROMPT WHERE YOUR FILE IS LOCATED. (right click while pressing shift)
STEP 2: THEN USE THE FOLLOWING COMMANDS TO EXECUTE.
(lets say the file and class name to be executed is named as Student.java)The example program is in the picture background.
javac Student.java
java Student
As of Java 9, the JDK includes jshell, a Java REPL.
Assuming the JDK 9+ bin directory is correctly added to your path, you will be able to simply:
Run jshell File.java — File.java being your file of course.
A prompt will open, allowing you to call the main method: jshell> File.main(null).
To close the prompt and end the JVM session, use /exit
Full documentation for JShell can be found here.
Now (with JDK 9 onwards), you can just use java to get that executed.
In order to execute "Hello.java" containing the main, one can use:
java Hello.java
You do not need to compile using separately using javac anymore.
You can actually run Java program as you would shell or python scripts without manually compile the Java file, as described in
JEP 330. That is available since JDK 11.
If you create a file testing, and put the following you should be able to run it as command testing. You need to make it executable in Linux and Mac OSX with chmod +x testing.
#!/usr/bin/env java --source 11
public class Test {
public static void main(String [] args) {
System.out.println("Hello world!");
System.exit(0);
}
}
You are not allowed to use the file extension .java in the previous example.
$ chmod +x testing
$ ./testing
Hello world!
$
But you can still execute if it is was name Test.java without the shebang "#!" prefix like this:
public class Test {
public static void main(String [] args) {
System.out.println("Hello again!");
System.exit(0);
}
}
Then execute the file Test.java with following command:
$ java Test.java
Hello again!
$
So this works as long as you have a new enough Java compiler in the path, check with java -version. More information in this blog.
I have done a lot of researching on this concept but I can't seem to run a java program on the command prompt. Let's say we had a simple program like this:
public class Hello_World {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
On the command prompt I tried:
javac Hello_World.java
But I get:
'javac' is not recognized as an internal or external command, operable program or batch file
So I compiled it on BlueJ and then did this:
java Hello_World.java
But it said "cannot load or find main class Hello_World"!
I am currently using Windows 7, and made the programs on Notepad++ and BlueJ (to compile).
Any suggestions? Thanks!
This explains in detail what you have to do to set class path. Primarily you need to set your environment variables so that your shell finds the right directory containing javac to compile your program
javac' is not recognized ..
comes when you haven't point your java bin directory to your path environment variable. Because bin directory is the place where javac.exe exist.
To do it.
1) right click on mycomputer property
2) go to Advance system settings.
3) go to environment variable.
4) In system variable click on path
5) go to edit mode and provide your path to java bin directory.
in my case it is C:\Program Files\Java\jdk1.7.0_01\bin;
'javac' is not recognized as an internal...
means OS does not know where javac program is located. Either add it to PATH or run explicitly
my\path\to\file\javac Hello_World.java
Compiling will convert *.java to *.class
Hello_World.class file should be located according to it's package directive. Since you have no one, in your case it should be located in the same directory you will run java.
To run your class specify it's name not file name
java Hello_world
looking for the class is essential part of launching and occurs by rules.