Java application only works when launched via a terminal/command prompt - java

I'm recently starting to learn Java and have had success writing and compiling my own application (written in Sublime Text, a text editor, and compiled via javac).
The application runs perfectly when launched via a terminal (or command prompt if I'm on my Windows PC), but if I try launching it from the file itself (in Windows, double clicking it and ensuring Java is the open-with method, or on my Ubuntu laptop, making it executable and doing the same) I get a very short lived loading cursor and then nothing.
The application (which converts between degrees Celsius and Fahrenheit) uses some simple Swing dialogs to get the user's input and to display the result.
import javax.swing.*;
public class DegreesConversion
{
public static void main( String [] args)
{
String input = JOptionPane.showInputDialog("Enter a temperature followed by either C for Celcius or F for Fahrenheit\nE.g. 30C or 86F");
int degrees = Integer.parseInt(input.substring(0,input.length()-1));
switch (input.toLowerCase().contains("f") ? 0 : input.toLowerCase().contains("c") ? 1 : 2){
case 1:
JOptionPane.showMessageDialog(null,(((degrees*9)/5)+32)+" degrees Fahrenheit", "Conversion complete", JOptionPane.INFORMATION_MESSAGE);
break;
case 0:
JOptionPane.showMessageDialog(null,(((degrees-32)*5)/9)+" degrees Celcius","Conversion complete",JOptionPane.INFORMATION_MESSAGE);
break;
default:
JOptionPane.showMessageDialog(null, "The input you entered was not recognised!","Unknown input", JOptionPane.ERROR_MESSAGE);
break;
}
}
}
(This is by no means meant to be a serious or terribly functional application, it was simply my own attempt at making something in Java)
Anyhow, I'm not sure why this application, when compiled, only functions when launched from a CLI using "java DegreesConversion", and not when launched through a double click. I have looked for answers regarding this on Google and Stackoverflow, but haven't found anything near a relevant solution or hint as to why this is so.
I'm considering that Java .class files can't be executed the same as .jars?
Any assistance would be greatly appreciated!

Package your class into a jar file and add a manifest to it pointing to the class having the main method you like to execute.
Then you can do java -jar jarFile.jar from terminal but it is also possible to easily to run it through, e.g., Windows Open-With capabilities.
EDIT:
JAR tutorial

Related

How to log executed lines of code and variables at that point in Java?

I'm working on a project for my Uni where I want to visualize code debugging. For this I somehow need to log the executed Lines of Code and the variables with their values for a given Java program. An example:
public class Main {
public static void main(String[] args){
String abc = "def";
String test = "hello world";
String foo = abc+test;
}
}
If i log this programm my output should be something like this:
Main at line 3:
Main at line 4: abc=def
Main at line 5: abc=def,test = hello world
Main at line 6: abc=def, test = hello world, foo = defhello world
The logging program should run in the background so I can use the logged program normally.
I already tried stuff with Java Agents and Stacktrace but I could'nt get good results. I hope there is any way to do this. Thanks for any help in advance!
There are ways to do this, some IDE like Intelij IDEA actually display the variable value in the editor when you debug.
But if you want to log that, not only the information log would soon become huge (gigabytes/terabytes for real programs) but it would be quite complex.
Here several ways to do this:
Actually use the debugger API to interract with the running program and so log that information: https://docs.oracle.com/javase/8/docs/technotes/guides/jpda/index.html
Make it with a plugin to the compiler so it add the necessary logs. I think that was your approach.
Create a Java => Java compiler that add the matching source and let the standard compiler compile the java. For that there an open source API for eclipse I think that they use for refactoring in the IDE. (Here a blog post that show you can use the API to read java code: https://www.vogella.com/tutorials/EclipseJDT/article.html)

Can't run Oracle suggested JAVA code in Eclipse [duplicate]

This question already has answers here:
System.console() returns null
(13 answers)
Closed 5 years ago.
I'm trying to learn Regular Expressions in JAVA, it was suggested I copy and compile code in my preferred IDE (Eclipse) to test how the API works.
Source: https://docs.oracle.com/javase/tutorial/essential/regex/test_harness.html
When I run, my IDE simply says "No Console" in the output.
I've written many programs from the online classes I've been taking for JAVA, never encountering a situation where the console is not recognized. I have exported those compiled projects as runnable .jars and never had a problem from the command line executing only the jar file name. I have found when exporting as a runnable .jar - for this specific jar file - to preface executing on the command line with --> java -jar <*runnable.jar*>.
That works ... running from my IDE does not.
Perhaps obviously, I'm a newbie to OOP, and I've searched everywhere (including on your site), and don't have a clue. I am running the Mars 2 (4.5.2) version of Eclipse on a Windows 7 64-bit machine; JRE/JDK 8; along with a JAVA_HOME ENV setup.
Can someone give me an idea as to which properties to change in the IDE settings for Eclipse? Or perhaps, the Oracle code needs to be augmented for my particular environment?
This tutorial uses System.console(), but this requires an actual terminal, and that won't work when running in an IDE. That's a shame because it could very well read from System.in & print to System.out instead.
Here is a replacement that will work in Eclipse or any good IDE:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class RegexTestHarness {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("\nEnter your regex: ");
Pattern pattern =
Pattern.compile(input.nextLine());
System.out.println("Enter input string to search: ");
Matcher matcher =
pattern.matcher(input.nextLine());
boolean found = false;
while (matcher.find()) {
System.out.printf("I found the text" +
" \"%s\" starting at " +
"index %d and ending at index %d.%n",
matcher.group(),
matcher.start(),
matcher.end());
found = true;
}
if(!found){
System.out.println("No match found.\n");
}
}
}
}

Java check if program is installed on windows

Is there a way to check if a specific program is installed on Windows using Java?
I'm trying to develop a Java program that automatically creates zip archives by using the code line command from 7-Zip.
So, I would like to check in Java if on my windows OS '7-Zip' is already installed. No check for running apps or if OS is Windows or Linux. I want to get a bool (true/false) if '7-Zip' is installed on Windows.
The library Apache Commons has a class called SystemUtils - full documentation is available at https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/SystemUtils.html.
In this library you have the following static boolean properties at your disposal:
SystemUtils.IS_OS_LINUX
SystemUtils.IS_OS_WINDOWS
The unix-like solution would be to simply try to run the program with --version flag (on windows probably the /? or - like in the 7zip case - without any at all) and check whether it fails, or what the return code will be.
Something like:
public boolean is7zipInstalled() {
try {
Process process = Runtime.getRuntime().exec("7zip.exe");
int code = process.waitFor();
return code == 0;
} catch (Exception e) {
return false;
}
}
I assume that you're talking about Windows. As Java is intended to be a platform-independent language and the way how to determine it differs per platform, there's no standard Java API to check that. You can however do it with help of JNI calls on a DLL which crawls the Windows registry. You can then just check if the registry key associated with the software is present in the registry. There's a 3rd party Java API with which you can crawl the Windows registry: jRegistryKey.
Here's an SSCCE with help of jRegistryKey:
package com.stackoverflow.q2439984;
import java.io.File;
import java.util.Iterator;
import ca.beq.util.win32.registry.RegistryKey;
import ca.beq.util.win32.registry.RootKey;
public class Test {
public static void main(String... args) throws Exception {
RegistryKey.initialize(Test.class.getResource("jRegistryKey.dll").getFile());
RegistryKey key = new RegistryKey(RootKey.HKLM, "Software\\Mozilla");
for (Iterator<RegistryKey> subkeys = key.subkeys(); subkeys.hasNext();) {
RegistryKey subkey = subkeys.next();
System.out.println(subkey.getName()); // You need to check here if there's anything which matches "Mozilla FireFox".
}
}
}
If you however intend to have a platformindependent application, then you'll also have to take into account the Linux/UNIX/Mac/Solaris/etc. (in other words: anywhere where Java is able to run) ways to detect whether FF is installed. Else you'll have to distribute it as a Windows-only application and do a System#exit() along with a warning whenever System.getProperty("os.name") is not Windows.
Sorry, I don't know how to detect in other platforms whether FF is installed or not, so don't expect an answer from me for that ;)

Using XLLoop for java

XLLoop is opensource framework to java. For example we can use function from java in excel. Below is very simple example of usage:
package org.boris.xlloop.util;
import org.boris.xlloop.FunctionServer;
import org.boris.xlloop.handler.*;
import org.boris.xlloop.reflect.*;
public class ServerExample
{
public static void main(String[] args) throws Exception {
// Create function server on the default port
FunctionServer fs = new FunctionServer();
// Create a reflection function handler and add the Math methods
ReflectFunctionHandler rfh = new ReflectFunctionHandler();
rfh.addMethods("Math.", Math.class);
rfh.addMethods("Math.", Maths.class);
rfh.addMethods("CSV.", CSV.class);
rfh.addMethods("Reflect.", Reflect.class);
// Create a function information handler to register our functions
FunctionInformationHandler firh = new FunctionInformationHandler();
firh.add(rfh.getFunctions());
// Set the handlers
CompositeFunctionHandler cfh = new CompositeFunctionHandler();
cfh.add(rfh);
cfh.add(firh);
fs.setFunctionHandler(new DebugFunctionHandler(cfh));
// Run the engine
System.out.println("Listening on port " + fs.getPort() + "...");
fs.run();
}
}
I understand it and generally programm is working. But if I go to excel, it isn't working.
I try:
=FS("Math.random")
=Math.random()
But I got #NAME? twice
So I suppose that I should make something yet. Could you tell me step by step how configure excel and java to do this? What should I do with xlloop-0.3.2 (Microsoft Excel XLL Add-In) file ?
I tried running the code and I got the following output.
All I had to do was to launch Excel and add the XLLoop addin.
. Press Alt+G or click on the Go button beside Manage Excel Add-ins.
. Click on Browse and provide the path to the xlloop-0.3.2.xll file. If you had downloaded xlloop-0.3.2.zip,extract it and you will find it inside /xlloop/bin
Hope that helps.
Edit:
Launch Excel.
Start the server(run the Main class) and test the formulas.
I tested the following 2(typed them on the Excel formula bar and hit/press Enter) and it worked fine. :)
=FS("Math.sin", 3.14)
=FS("Math.random")
For anyone running into the same problem:
You have to add the correct Addin Version to your excel installation.
If you are getting the error message: "The file format and extension [...] don't match.", it means that you are using a 64bit excel and the 32bit XLLoop addin.
You have to either install a 32bit Excel, or you have to get the 64bit version of the XLLoop Plugin.
We ran into the same problem, and created a 64bit version of the addin: https://github.com/PATRONAS/xlloop

How to open user system preferred editor for given file?

I'm trying to figure out how to open the system preferred editor for a given file.
Say, we have a file manager, written in Java. User goes to folder and sees the list of files. And, for example, there is a file Icon.jpg. User double clicks on the filename and file opens in system's preferred editor (i.e. Gimp). The main issue is - how to do that?
We can do Runtime.getRuntime().exec("something file"), but this way you should know which program is preferred in user environment. But how?
We also are able to do Desktop.getDesktop().edit(File file), but this way we cannot track process and aren't able to know then this child process is closed. Other issue - function doesn't work on linux (at least on Ubuntu 8.10). There is also Desktop.getDesktop().open(File file), but it forces to open file viewer, instead of system viewer for that file type.
I am searching for a solution all week, but didn't got any suitable and generic one. Do you know the other approaches to this question? For my project it would be enough if it would work on Windows+Linux+Mac.
Thank you for your answers and advices.
Edit on 2009-02-08 23:04
Other suggestion: can I force "application selection" window in Windows and in Linux, as in Mac with "open file"? For example, then you trying to open file, you are being asked to choose application from list of system preferred ones? (something like "Open with..." in Windows explorer). Do you know?
Seems that if you can't use java.awt.Desktop you have to distinguish between the OSes:
Windows:
RUNDLL32.EXE SHELL32.DLL,OpenAs_RunDLL <file.ext>
Linux:
edit <file.ext>
Mac:
open <file.ext>
HTH. Obviously, that is not very portable...
Check out the java.awt.Desktop object. In your case, you want to invoke edit()
If you want to ensure that a given platform supports this call, then you can do something like the following (I have not tested this code):
public boolean editFile(final File file) {
if (!Desktop.isDesktopSupported()) {
return false;
}
Desktop desktop = Desktop.getDesktop();
if (!desktop.isSupported(Desktop.Action.EDIT)) {
return false;
}
try {
desktop.edit(file);
} catch (IOException e) {
// Log an error
return false;
}
return true;
}
This isn't cross-platform, but on Mac OS X you can do
Runtime.getRuntime().exec("open filename");
The open(1) executable uses LaunchServices to pick the right program to execute, and then uses that to open the file named filename.
This will work in windows
Runtime.getRuntime().exec( "CMD /C START filename.ext " );
For JavaFX applications, we can use HostServices. This question covers how to use HostServices. This should work on Ubuntu (tested)/Windows (not tested) and Mac (not tested).
import java.io.File;
import java.io.IOException;
public class App extends Application {
}
File file = new File("/your/file/path");
HostServices hostServices = getHostServices();
hostServices.showDocument(file.getAbsolutePath());
getHostServices() is a method of JavaFX Application class.

Categories

Resources