I want to run .exe application with two parameters.Its VB .exe application its need two parameters to execute ? I tried with create .cmd file to execute .exe application, its working good.
Please see the which code running .cmd file.
start xx.exe ./aa.txt,2012
Same procedure following in java, but giving error...
Please find the below small java program.
public class Invoke
{
public static void main(String as[])
Runtime r=Runtime.getRuntime();
Processp=null;
try
{
String s="...complie.exe";
String d="...de.txt";
String l="...foldername";
p=r.exec(s,d,l);
}
catch(Exception e){
}
Please advise...
Here is an example how to start jEdit program and some txt file from Java:
import java.io.IOException;
public class Invoke {
public static void main(String[] args) {
try {
Runtime.getRuntime().exec("C:/Program Files/jEdit/jedit.exe");
Runtime.getRuntime().exec("notepad C:/Program Files/TechSmith/Camtasia Studio 7/TSCCinst.txt");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Related
Here is my code
package vista;
public class MyMainClass
{
public static void main(String[] args)
{
try
{
if(1>0) throw new MyException("ERROR");
}
catch(MyException err)
{
System.out.println(err.toString());
}
}
}
package vista;
public class MyException extends Exception
{
// Constructor.
public MyException(String errMsg)
{
super(errMsg);
}
}
Output:
Error: Unable to initialize main class vista.MyMainClass
Caused by: java.lang.NoClassDefFoundError: vista/MyException
Command execution failed.
Both classes are in the same \vista folder, and before excecution NetBeans recognizes this. How do I resolve this?
Edit: while not running but just compiling the program I realized NetBeans was attempting to download some files. I turned my firewall off, ran the program, it downloaded some files, and now it excecutes properly.
Simple question here. Here is my Java file:
public class Test {
public static void main(String []args) {
System.out.println("It ran!");
}
void a() {
qweifjew;
}
}
When I press "Run" on VS Code, it says build failed do you want to continue? Makes sense since I have compile-time errors. But when I press continue, it is still able to run and display "It ran!". How come?
For more information on the run command:
C:\Users\jeffe\coding-tutorials\learning-jest> cd c:\Users\jeffe\coding-tutorials\learning-jest && c:\Users\jeffe\.vscode\extensions\vscjava.vscode-java-debug-0.27.1\scripts\launcher.bat "C:\Program Files\Java\jdk-11.0.2\bin\java.exe" -Dfile.encoding=UTF-8 -cp C:\Users\jeffe\AppData\Roaming\Code\User\workspaceStorage\5e0a770d0910238b624ead6f98bca1ec\redhat.java\jdt_ws\learning-jest_f8aabfb2\bin Test
It ran!
This is the decompiled .class file of your code:
public class Test {
public Test() {
}
public static void main(String[] args) {
System.out.println("It ran!ddfseffe");
}
void a() {
throw new Error("Unresolved compilation problems: \n\tSyntax error, insert \"VariableDeclarators\" to complete LocalVariableDeclaration\n\tqweifjew cannot be resolved\n");
}
}
You have Auto Save ON in VS code ?
It's able to run a previous successful build to give you an output.
I've got a tough question, for which I will first sketch a background to make things more understandable.
Background
I have made an audioplayer in Java which can be launched with command line args, and also without. The application's .jar (made with Netbeans) is wrapped in a .exe file (made with Launch4j) so that you can open for example a mp3 file with the .exe, and then the .jar inside adopts the filepath in it's String[] args.
The problem with this approach (for now) is that if you select multiple mp3 files at once and you open them at the same time, they all get opened in seperate windows of the audioplayer. What I want however, is that all the files get opened in one single instance of the application.
What I then attempted is to let Launch4j allow only one instance of the .jar/.exe in the hopes that all the selected files would be opened in one application, this did unfortinately not work.
What I see as a solution
So I want to be able to select multiple .mp3 files in windows, and that all their filepaths get passed on as a command line arg to one single instance of the application. Or a different approach that has the same result. Does anyone know how to realize this in the actual application?
Many thanks in advance. I will try to keep looking for potential solutions/ideas as well.
--Edits--
The main method is ready to receive multiple files. I have implemented a piece of code that saves all the command line args of the application to a .txt file, and when I allow only one single instance with the Launch4j .exe file, there only appears to be one single argument in the .txt file when I try to open multiple mp3 files.
If I allow the .exe to have multiple instances, then I simply have the .jar application being launched multiple times (one time for each file I try to open).
I used java RMI (Remote Method Invokation) to make a single-instance application.
An RMI attempts to listen on a socket with a user-defined port number.
When starting the jar.
If noone serves that port, then this instance is the RMI server. Establish a GUI Window. Call an open with the main's args.
If there is already a serving application, send by RMI an open with the main's args. Then exit normally, return from main.
Code: Untested as you probably want to arrange things differently.
public interface OpenRMI extends Remote {
void open(String[] args) throws RemoteException;
}
public class SingleInstanceApp implements OpenRMI {
private static final String RMI_ENTRY = "ImJustACowLolAudioPlayer";
public static void main(String[] args) throws RemoteException,
AccessException, NotBoundException {
System.out.println("main " + Arrays.toString(args));
if (System.getSecurityManager() == null) {
System.setSecurityManager(new SecurityManager());
}
Registry registry = LocateRegistry.getRegistry();
OpenRMI openRMI;
try {
System.out.println("bind with new OpenRMI");
SingleInstanceApp app = new SingleInstanceApp();
openRMI = (OpenRMI) UnicastRemoteObject.exportObject(app, 0);
registry.bind(RMI_ENTRY, openRMI);
System.out.println("Player bound");
app.create(); // Server.
} catch (AlreadyBoundException e2) {
System.out.println("lookup as someone else bound before us");
openRMI = (OpenRMI) registry.lookup(RMI_ENTRY); // Client.
}
openRMI.open(args);
}
private void create() {
new Thread(true) { // Daemon thread, or start GUI
#Override
public void run() {
System.out.println("create " + this);
for (int i = 0; i < 10; ++i) {
Thread.sleep(1000L);
}
shutdown();
}
}
}
private void shutdown() throws RemoteException,
NotBoundException, AccessException {
System.out.println("close " + this);
Registry registry = LocateRegistry.getRegistry();
registry.unbind(RMI_ENTRY);
}
#Override
public void open(String[] args) throws RemoteException {
System.out.println("open " + this + ": " + Arrays.toString(args));
}
}
I would expect some more decent classes.
I fixed it, after some hours of programming and taking breaks inbetween
package argsbuilder;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
public class ArgsBuilder
{
public static void main(String[] args)
{
checkIfRunning(args);
}
private static void checkIfRunning(String[] args)
{
buildFile(args);
ProcessBuilder pb = new ProcessBuilder("core.exe"); //core.exe is a .exe wrapper with the .jar audioplayer in it
try
{
Process p = pb.start();
}catch (IOException f){System.out.println(f);}
}
private static void buildFile(String[] args)
{
try
{
boolean notdone = true;
int i=0;
File f;
while(notdone)
{
f = new File("arg" + i + ".txt");
if(f.exists())
{
i++;
}
else
{
PrintStream out = new PrintStream(new FileOutputStream(new File("Folder Location" + "arg" + i + ".txt")));
System.setOut(out);
System.out.println(args[0]);
notdone = false;
}
}
}catch(Exception g){System.out.println(g);}
}}
What the above does
The above application checks if there are other argument files, and if there are it will keep generating a new name untill the name is free. It then prints the argument to that file. After it has printed the argument, it launches the audioplayer. In the audioplayer the following happens:
import javafx.embed.swing.JFXPanel;
import java.net.InetAddress;
import java.net.ServerSocket;
public class YourApp {
public static void main(String[] args)
{
try
{
socket = new ServerSocket(PORT,0,InetAddress.getByAddress(new byte[] {127,0,0,1}));
//Everything you need to launch the application in the try
}catch(Exception g){//Nothing in the catch}
}}
What the above does
It tries to claim a serversocket for itself. If there already is one then it does not proceed to launch the application. That way only one instance will be running at a time. (at PORT you just fill in a random integer).
Combining those 2, you can read the textfiles created by the first application and interpret them as arguments in the second application.
So how does it interpret them as arguments?
Well, I already had a timer fixed into the program, and I tell the audioplayer to look for the very first arg file (arg0.txt) in a specified folder. If it finds it it adds it to an arraylist, along with all arg+i.txt files.
It might not be the fastest way, but it surely works well.
I have written a Java program that should open another program (which is a .jar file). If I use this code in the main class of my program, all works correctly:
File logFile = new File("./ePaymentUpdater.jar");
Desktop.getDesktop().open(logFile.getCanonicalFile());
//or
Runtime.getRuntime().exec("java -jar ePaymentUpdater.jar");
But if I paste the same code in the event in response to the user clicking a button, it doesn't work as it should:
The program seems to run, because it creates a folder like it should be (this code is in the main class of the called program), but it doesn't show the jFrame it should
It seems that i cannot open a frame from inside the frame of another program...
This is my main class:
package prove_idiote;
import java.awt.Desktop;
import java.io.File;
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
// try {
// Runtime.getRuntime().exec("java -jar ePaymentUpdater.jar");
// } catch (Exception e) {
// System.out.println(e);
// }
Tester tester = new Tester();
tester.setVisible(true);
}
}
And this is my button event:
private void ExecuteActionPerformed(java.awt.event.ActionEvent evt) {
try {
JOptionPane.showMessageDialog(null, "before" ,"ATTENZIONE!",JOptionPane.WARNING_MESSAGE);
Runtime.getRuntime().exec("java -jar ePaymentUpdater.jar");
JOptionPane.showMessageDialog(null, "after" ,"ATTENZIONE!",JOptionPane.WARNING_MESSAGE);
} catch (Exception e) {
System.out.println(e);
}
}
You can use the Runtime class of java and process your jar from there as follows:
Runtime.getRuntime().exec("java -jar ./ePaymentUpdater.jar")
Where Runtime handles all the processes at runtime and executes them one by one.
I finally found the problem (and the solution)
There were some missing libraries in the called .jar (i've put the two jars in the same folder, so they shared the same libs, but one of them was using a lib that was missing)
Thnaks for the hints
Runtime.getRuntime().exec("java -jar yourjarfile")
My Goal
I am attempting to make a Java program in which a user can select any .class or .jar file from their computer. My program will then pop up a JInternalFrame with a JEditorPane in it as the console, capturing any console output from the user's program. When the user's program closes (calls System.exit(int status);), my program must not close along with it. My program might also have such features as a button to immediately stop the user's program and others an IDE would. My program need not compile Java code, only run .class and .jar files.
My Experience
I have made a small test version of this program wherein I got two specific files from a package and had the user click one of two buttons, each representing one of the two programs. A press of a button calls the following method:
private void run(Class runnable)
{
java.lang.reflect.Method[] m = runnable.getMethods();
boolean hasMain = false;
for (int i = 0; i < m.length; i++)
{
if (m[i].getName().equals("main") && m[i].getParameterTypes()[0].isArray() && m[i].getParameterTypes()[0].getName().contains("java.lang.String"))
try
{
Object invoke = m[i].invoke(null, (Object)globalArgs);
hasMain = true;
hub.setExtendedState(Hub.ICONIFIED);
numPrograms++;
}
catch (Throwable t)
{
java.util.logging.Logger.getLogger(Hub.class.getName()).log(java.util.logging.Level.SEVERE, null, t);
javax.swing.JOptionPane.showMessageDialog(null, "Could not run " + runnable.getName(), "Error in invocation", javax.swing.JOptionPane.ERROR_MESSAGE);
}
finally
{
break;
}
}
if (!hasMain)
javax.swing.JOptionPane.showMessageDialog(null, runnable.getName()
+ " does not have a public static main method that\nreturns void and takes in an array of Strings",
"No main method", javax.swing.JOptionPane.ERROR_MESSAGE);
}
This method successfully calls either program's main method and runs a copy of said program. However, when any of the programs this hub has started calls the System.exit(int status) command, the hub closes, too. Also, I haven't the slightest clue as to how to capture console output.
My Questions
Does anyone have any experience or advice they would be willing to share to help me make a fully-functional program that can...
Open and run a compiled Java file (remember that .jar files may have more than one class with main(String[] args) method)
Catch System.exit(int status); so that the hub program handles the internal program's exiting
Catch new java.io.PrintStream().println(Object o) and similar calls and place their output in a JEditorPane
Make a button that, when pressed, stops the internal program from running
Possibly make all JFrames the internal program uses into JInternalFrames and place them in a JDesktopPane
If you don't want the other program (which you call through it's main method) to be able to shut down the JVM you're running in, you have, as I see it, three options:
1. Using a SecurityManager
Set up the SecurityManager so that it prevents the System.exit call:
public class Test {
public static void main(String args[]) {
SecurityManager sm = System.getSecurityManager();
System.setSecurityManager(new SecurityManager() {
#Override
public void checkExit(int status) {
throw new SecurityException("Client program exited.");
}
});
try {
System.out.println("hello");
System.exit(0);
System.out.println("world");
} catch (SecurityException se) {
System.out.println(se.getMessage());
}
}
}
Prints:
hello
Client program exited.
This is probably the nicest solution. This is the way application servers prevent an arbitrary servlet from terminating the entire server.
2. Separate JVM
Run the other program in a separate JVM, using for instance ProcessBuilder
import java.io.*;
public class Test {
public static void main(String args[]) throws IOException {
ProcessBuilder pb = new ProcessBuilder("java", "other.Program");
pb.redirectErrorStream();
Process p = pb.start();
InputStream is = p.getInputStream();
int ch;
while ((ch = is.read()) != -1)
System.out.print((char) ch);
is.close();
System.out.println("Client program done.");
}
}
3. Use shutdown hooks instead
Don't disallow the termination of the JVM, but instead add shutdown-hooks that cleans up the "hub" and exits gracefully. (This option probably only makes sense if your running one "external" program at a time.)
import java.io.*;
public class Test {
public static void main(String args[]) throws IOException {
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
System.out.println("Uninitializing hub...");
System.out.println("Exiting gracefully.");
}
});
// Run client program
System.out.println("Running... running... running...");
System.exit(0);
}
}
Prints:
Running... running... running...
Uninitializing hub...
Exiting gracefully.