VS Code runs .java files without the producing .class files - java

I have some basic java knowledge and i decided to switch from Intellij to VS Code. I know how to compile and run a java file (which may use other imported .java files) from the terminal, but i want to run a java program using the run icon inside vs code.
I'm not a 100% sure, but i think that in order to run a java program inside vs code you need a extension. For this reason i downloaded the Java extension pack. Note that i already have installed the latest jdk on my computer.
After i installed the plugin, i could run the program using the "run without debugging"/clicking in the run icon. However, no .class files are produced. I control+h but there isnt any hidden folder that vs code may drop the .class files.
How does the program run in the first place?
How can i config vs code in order to compile the java files before running the one that has the main function?

Basically, when you run a java file normally, you compile it with javac and then run it with java (or something along those lines, there are many different variations of possible ways to do it). If you go ahead and try, it is possible to run java filename.java and skip the normal javac step. In the case of VSCode, it will differ based on what extensions you have, but some may run the code with a simple java filename.java and others may have different settings set. If you take a look at your extension preferences as well as your preferences for java by searching your settings, there may be an option, such as "Java Source Paths" enabled which changed where compiled files are saved by VSCode.

If your project is a folder containing Java source files. And no build tools(Maven/Gradle) are used.
If that is the case, you can trigger the command Java: Configure Classpath, then find the section output and then set a relative path to your workspace.
The output files are by default stored inside the workspace storage.
If after triggering the command, what you see is the native vs code setting page. Then try to search java.project.outputPath and then set a relative path to it.

Related

Fiddly thing to do with \bin directory in Eclipse

This has really got me baffled.
In my Eclipse workspace I have a project called "Java scratchpad". In "Package Explorer" you see "src" (Source Folder) under this and then "root" (Package). Under "root" is a .java file called "LoggingTest.java".
So the path to this java file is "G:\My Documents\software projects\workspace\Java scratchpad\src\root\LoggingTest.java".
When I run the following code in Eclipse:
Path currentRelativePath = Paths.get("");
String s_currRelPath = currentRelativePath.toAbsolutePath().toString();
String pathWithForwardSlashes = s_currRelPath.replace( "\\", "/" );
System.out.println( "path " + pathWithForwardSlashes );
The result is
path G:/My Documents/software projects/workspace/Java scratchpad
But... when I am running the same piece of code at the Command Prompt I have to start in the following directory:
G:\My Documents\software projects\workspace\Java scratchpad\bin
... and then go > java root.LoggingTest at the prompt.
The output from the above bit of code is then:
path G:/My Documents/software projects/workspace/Java scratchpad/bin
In other words, when you run the thing at the Command Prompt you are running a .class file under the \bin directory, but when you run in Eclipse, the Eclipse framework "pretends" that the bin directory doesn't exist.
And the upshot is that I get different values for the "current relative path" (CWD) depending on whether I'm running in Eclipse or at the Command Prompt. If I want to make or use a directory relative to the CWD I'm going to get different values depending on whether I'm running in Eclipse or at the Command Prompt.
I'm feeling quite slow tonight. What should I do? Is there a way of detecting whether a project is being run in Eclipse or at the Command Prompt? Or should I simply try to detect whether the path ends in "\bin" and remove those four characters to make the paths equivalent?
later
Just adding a note in reply to the comment from E-Riz:
It's a simple thing: I want to create logs and I want to create Lucene indices... and to keep things in one location (at this stage anyway) I just want to put this output in a location such as ...\Java scratchpad\output\indices\[name of index] or, respectively, ...\Java scratchpad\output\logging\[name of log].
And, yes, of course at present I do know the absolute path involved here... however, as the name suggests, this is a "scratchpad" or test area... so then this code which uses the CWD to determine where to put or find logs or indices can be used more generically, without having to know the absolute paths involved.
But it has to work either in Eclipse or at the command prompt...!
NB my current workaround is indeed to check whether pathWithForwardSlashes ends in "\bin", and if so to delete these last 4 chars. I can't be the only person to have encountered this oddity. Bet there are cleverer solutions!
There's a couple of facts that you should know or keep in mind:
At runtime, Java can (should) be given a classpath to work with; the default application classpath is just . (the current directory where java was invoked from). That's why it seems to you that you must run your program from the \bin directory of your project; because you haven't told the JVM anywhere else to look for classes. You should be setting the runtime classpath when running your application, which can be done a variety of ways but for simple programs is often done via a batch file or shell script. Note that using -cp to specify the classpath will be crucial when you depend on any JARs.
In Eclipse, since applications aren't run via a command-line, Eclipse has Launch Configurations that encapsulate all the details necessary for launching a program (in "run" or "debug" mode). Here's a decent tutorial (although a bit dated; you can find lots more info about Launch Configurations out there on the Interwebs. The key piece of configuration you're looking for is on the Arguments tab, where you can specify the working directory for a program launch config. The default is the project's root directory. See how that's different than when you've been running your on command line? That explains the difference you're seeing in output. You could change the working directory in the Eclipse Launch Configuration, but I tend to prefer to keep it as the project root.
So, you have a couple of options to make things consistent: use a script/batch to run your app on the command-line, specifying -cp so the JVM knows where your class files are (and any other JARs it might need down the road, too); or, reconfigure your Eclipse launch to match where you run from on the command line. I think the (by far) preferable option is the first one.
Having said all that, you should usually not need to do any path manipulation at all when it comes to files/resources in Java. Everything is relative to either the current working directory where Java was run from, or the classpath.

How to run Java programs by clicking on their icon on Windows?

I have written a Java program that uses Java swing library. Now I would like to execute this program by double clicking on the executable file on Windows just like any other program with a GUI. How do I do that?
Since it is Java based and has a GUI, the obvious answer is to deploy it using Java Web Start.
Java Web Start (JWS) is the Oracle Corporation technology used to launch rich client (Swing, AWT, SWT) desktop applications directly from a network or internet link. It offers 'one click' installation for platforms that support Java.
JWS provides many appealing features including, but not limited to, splash screens, desktop integration, file associations, automatic update (including lazy downloads and programmatic control of updates), partitioning of natives & other resource downloads by platform, architecture or Java version, configuration of run-time environment (minimum J2SE version, run-time options, RAM etc.), easy management of common resources using extensions..
By 'desktop integration' read desktop shortcuts and menu items on supported platforms.
The 2 icons on the right (JotPad & Star Zoom Animation) are both Java based apps., installed using Java Web Start. Since JotPad is sand-boxed, the user will be prompted as to whether to create the shortcut. That choice is not offered for apps. with higher permission levels, so it would make more sense to install/remove the shortcuts and menu items using the IntegrationService - which allows an app. (after prompting the user) to create/remove them at run-time.
There are number of options:
Create an executable jar of your project. for this jar to work you have to have javaw as default application to open it.
Create an exe of your project.
Create a bat file which runs your jar file.
Take a look at this: How can I convert my Java program to an .exe file?
While the others mention excellent choices like creating a native executable, there is another useful method: creating a shortcut.
Right click your desktop, expand the "New" option, and click on "Shortcut".
Type "javaw.exe". Click next.
Name it whatever you want. Click done.
You'll notice the newly created shortcut on your desktop. Right click it and choose "Properties"
In the "Target" textfield, append "-jar path-to-your-jar.jar" where you replace "path-to-your-jar.jar" with the actual path to your jar
You can also now optionally change the icon to whatever icon you want
This shortcut can be pinned to the taskbar and be used from anywhere (considering you provided an absolute path to your JAR).
you need to create exe from the java program.
Creating executable jar files
First, make sure you have installed Java 1.2 or above. This facility is not available in previous versions of Java.
Next, create your working java system. In general, you will want to put it into a package. For this example, I created a trivial HelloWorld application that prints out "Hello World" plus the first command line argument, and placed it into the package "psae". Therefore, the HelloWorld files (HelloWorld.class, HelloWorld.java) were located in the directory psae. I tested the system to make sure it worked before going on to the next step.
In the directory in which the psae is located, created a file called "mainClass". This file contains a single line specifying where the main Class is to be found in the jar file. Note that I use the package specification. Here is the single line:
Main-Class: psae.HelloWorld
Note: make sure you type a carriage return after this line; some windows systems need it and will report a "Failed to load Main-Class manifest attribute" error.
Next, I create a jar file called psae.jar using the "jar" command in Java2. I use the "m" command line argument to specify the manifest file mainClass, which adds information to the jar file on where the main class will be found. Here is the jar command:
bertha:~ > jar cmf mainClass psae.jar psae
Just for fun, and to check what's happened, I print the table of contents for the jar file I just created. Here's the command and its result:
bertha:~ > jar tf psae.jar
META-INF/
META-INF/MANIFEST.MF
psae/
psae/HelloWorld.java
psae/HelloWorld.class
Having successfully created the jar file, I can now invoke java2 on it with the command line argument:
bertha:~ > java -jar psae.jar Philip
Hello World Philip
There are a few projects, like http://jsmooth.sourceforge.net/ and http://launch4j.sourceforge.net/
you can use something like Launch4j.
also look at JSMooth.
Hope it helps
There are two ways. Both involve packaging your code in a .jar.
The first way is to build an actual .exe file using a tool like Launch4j. It will require you to set up things like tell it which class to execute, which icon to use, which JRE is OK, what JRE parameters to use, etc.
The second option is to make the .jar itself executable. You do this by adding a manifest to the .jar. The manifest is a small configuration file that describes the jar. One of the attributes is Main-Class which defines the entry point. In other words, it says which class has the main function that should be called when the user double-clicks the file.
Here's a basic tutorial about manifests: http://docs.oracle.com/javase/tutorial/deployment/jar/manifestindex.html
The 2nd option is easier to get going, but users will know what to do with a .exe far more often.
Note that if either approach complains that it can't find the class, make sure to set the classpath manifest attribute to match your project.
If you have an executable jar file, just shift-right click on your file and set it to be opened by javaw. The other option (in case you want to pass in parameters to your application) is to create a .bat file where you spin off your application via java or javaw
Right click to your "project" in eclipse and select "export" then choose "Java->Runnable Jar File" select your project name and finish.
Seems you want to deploy and run the standalone application of swings. Being a java developer you should understand the power of jar files. Those are executable in themselves {so no need to create .exe files :)} .
The below code will help you to create a jar file.
Creating a jar File in Command Prompt
Start Command Prompt.
Navigate to the folder that holds your class files:
C:\>cd \mywork
Set path to include JDK’s bin. For example:
C:\mywork> path c:\Program Files\Java\jdk1.5.0_09\bin;%path%
Compile your class(es):
C:\mywork> javac *.java
Create a manifest file:
C:\mywork> echo Main-Class: NameOfProject >manifest.txt
Create a jar file:
C:\mywork> jar cvfm NameOfProject.jar manifest.txt *.class
Test your jar:
C:\mywork> DanceStudio.jar
After creating a jar just double click on it and you are done.
You have to create an executable jar file. For that you just simply add a META-INF folder to the jar, then add a MANIFEST.MF text file with two lines:
Manifest-Version: 1.0
Main-Class: your.package.YourMainClass
Here's how to run a Java program by RIGHT-CLICKING on it (in other words, from the Windows Explorer context menu). This handy trick is great for beginners who need to test their simple programs on the fly. Works on both Win7 and XP rigs.
[ATTN: Depending on the situation, you may need to remove the package directive from the top of your Java file.]
Step 1. Create a batch file (e.g., RWJ.bat) inside a folder of your choice (say, in C:\Program Files\Java.)
Step 2. Fill RWJ.bat with the following commands (they will work just fine as is with simple classes but you can, of course, tweak them according to your particular needs by specifying compiler / interpreter switches, passing args, adding echo off, removing pause or whatever):
javac %1
java %~n1
pause
The first command passes the full name of your right-clicked file to the Java compiler; the second one strips the file extension and feeds JVM with the class name only.
Step 3. Add the following key to your Registry: HKEY_CLASSES_ROOT\*\shell\Run With Java and then create its command (default value):
C:\Program Files\Java\RWJ.bat %1.
Step 4. Run your Java class by right-clicking it and selecting Run with Java option.
That's all there is to it.
Another way to run Java programs by pointing and clicking is to use AOT compilers. For example, GCC has an entry point named GCJ, which can be used to compile the source code into both byte codes and standard executable file for your particular OS.
And finally, instead ot batch files one can run WSH, etc.

build multiple shared libraries

Hi I have a java program which has to invoke a native program, and this native program are given by two so files. So I create my so file in order to use this native program APIs to do something for my java program. I was trying to merge two so files with my created so file into single one, and run my java program. However, it seems that it failed this way. To be more concrete, here is my example.
I have a java program A which has to invoke some native code. Therefore I've written some native code and built it as a shared library (called: C.so).
Unfortunately, the native code I've written have to use other code which is in other so files. (A.so, B.so)
Thus, any ideas how to compile my so file with A.so and B.so in order to make my java program work?
I'm assuming the following:
When you link c.so, you are listing a.so and b.so on the command line.
When you run ldd on c.so, you see a.so and b.so.
When you run, you set -Djava.library.path to include the directory containing all three.
When you run, you do NOT set LD_LIBRARY_PATH to include the directory containing all three.
You will get the desired results if you set the LD_LIBRARY_PATH environment variable to include the directory with the libraries in it.
For more explanation, and an alternative, see https://github.com/bimargulies/jni-origin-testbed.

how to create a batch file to directly open the java console?

how can i create a ".bat" file to directly open the java console to write the programs?
for example:
c:\cd \program files\java\jdk1.6\bin
now ive entered the above mentioned folder, after that if i have to write a program a will type "edit"
i.e- c:\program files\java\jdk1.6\bin> edit
After doing all this, an application opens to write the programs....
Java doesn't have an interactive console for writing programs. You create them in any text editor (and there are hundreds of them to choose from), compile them via the javac compiler (usually, there are alternatives), and run them via the java command (or by wrapping them up as executable jar files).
There are development environments like Eclipse, Netbeans, and many many others that can make some aspects of this more convenient (like a button click to compile and run, code auto-completion, pop-up API reference, etc.).

Eclipse - Compiling & executing program

In the past, I have used JCreator to develop my java applications. I wanted to try Eclipse and see its IDE.
On JCreator, I could just open a java file and run it in the command prompt. On Eclipse, I cannot find out how I can compile and run a java file written by someone else without first creating a project, creating a new java class and then copy and pasting the code from the file.
I cannot even figure out how to import a java file into the project.
So my questions:
1. How can I open, compile and run a java file without first creating a java project.
2. How can I import a java file into a project I already have.
3. How can I run the program in command prompt, instead of on the console that is in Eclipse, (update: to be more clear) directly from the Eclipse.
Thank you.
1/ Do not forget scrapbook page (also presented here)
In theory, you could copy a class in it, but since that class is actually encapsulated into a "main invisible" class, as an inner class, it would not support any static methods in it.
However, for a quick chunk of code, it does the trick just fine.
(from this Eclipse tutorial)
3/ Since you want it run directly from eclipse, use as indicated in this thread, an External tool
That External Tool would run C:\WINDOWS\system32\cmd.exe with working directory ${container_loc}
More details in this article "How do I open a Windows Command Prompt in my console ?".
(source: avajava.com)
That will give:
(source: avajava.com)
As far as I know, you can't
Right click project > Import
With respect to your platform, something roughly equivalent to: java <classname>. (Make sure java is in your path, otherwise use the absolute path to the it.)
A useful feature is available in Eclipse since version 3.4: you can paste the text of a Java class into a Java project (copy the content of the class, select the project or source folder, paste). This will create an appropriately named file, in the correct package. This is probably the easiest way to import a single class.
2) Use the "Import" command. Ensure the java file goes to the "src" directory.
3) One way is to export your classes to a JAR file and then run the JAR file at the command prompt (e.g. java -jar file.jar)

Categories

Resources