I want to add arguments to my Java application before i run it. I want to be able do somthing like:
public static void main(String args[])
{
String document = args[0];
new DocumentViewer(document);
}
I want to do somthing like when you click on a Word document it opens up the document by itself, you dont have to open word and then click open. Does anyone know how to add arguments? All relevant answers are appriciated!
java YourClass yourfile.xtx
To associate your program with a file extension, so that it is automatically called, you have to configure your Desktop Environment (Linux) or Windows (Windows) (I don't know for OSX).
I don't have it in my head, but as far as I remember, you combine the extension, xtx for example, with a starting command, like
java -cp C:\Programs\yourlibs\your.jar YourClass %1%
If you have or can have more arguments (mark multiple files, and drag them to your starter) you can, afaik, go up to %9%:
java -cp C:\Programs\yourlibs\your.jar YourClass %1% %2% %3%
%1% is for the first param and so on.
There is nothing you can do from Java, except catching those parameter, what you already do.
On Linux, your starter is very similar:
java -cp /usr/local/lib/your.jar YourClass $1 $2 $3
If you're launching your app from the command line you could just pass the arguments separated by a blank space right after the application name like this:
java name_app arg1 arg2 etc...
//the code above passes to name_app 3 strings: "arg1", "arg2", and "etc..."
Not sure about what you want to do with Word but I hope this was helpful.
Java Web Start
..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..
For a demo. of the file associations, see the JNLP API file service demo.
The application that you are trying to create is a GUI application while the arguments that main method take is meant for Command Line interface input.
Where string [] args is the String array that can story many arguments from CLI. Of course you can implement the feature with a mix of CLI and GUI program but then you will be limited to launch your application from CLI, which doesn't make sense.
Another workaround can be. Create a demo frame that appears in the beginning have some textboxes and let users enter what you want to take as an argument, pass that value in the method, or data types you like. In that way you can have a full blown GUI application.
Related
From what I read, there are a couple of ways to run java files in a node.js application. One way is to spawn a child process: (the java code is packaged with dependencies in an executable jar.)
var exec = require('child_process').exec, child;
child = exec('java -jar file.jar arg1 arg2',
function (error, stdout, stderr){
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if(error !== null){
console.log('exec error: ' + error);
}
});
The other way is to use the java - npm module (link), a wrapper over JNI (this will let me create objects, set and get attributes, run methods).
In a production environment, when I want my node.js (Express) server to call a java program (it just saves an image to the local directory), please advise me on which would be the better way to accomplish this (in terms of best practices). Also, there is a long list of arguments that I need to pass to the main class and doing that on the command line is a bit of a struggle. Should I make the java program read from an input file instead?
1) If you use exec, you will run an entire program, whereas if you use a JNI interface, you'll be able to directly interact with the libraries and classes in the jar and do things like call a single function or create an instance of a class. However, if you don't need anything like that, I think using exec is far simpler and will also run faster. Sounds like you just want to run the Java application as a standalone process, and just log whether the application finished successfully or with errors. I'd say it's probably better to just use exec for that. Executing a child process this way is also far better for debugging, debugging JNI errors can be very difficult sometimes.
2) As for whether or not to read arguments from a file, yes, it's usually better to read from some sort of file as opposed to passing in arguments directly. It's less prone to human error (ie. typing in arguments every time), and far more configurable. If someone like a QA engineer only needs to edit a config file to swap out options, they don't need to understand your entire codebase to test it. Personally I use config files for every Java program I write.
You can use deployment toolkit and run the jar through jnlp. https://docs.oracle.com/javase/8/docs/technotes/guides/deploy/deployment_toolkit.html
Advantage of running jars through jnlp is the ability to pass parameters from javascript to your jar. In this way you can dynamically customize your java program.
For this kind of problem you'd want to approach it in the following way:
Is there a decent way to run processes with arguments in my language/framework
Is there a decent way to deal with the programs output?
From experience, a decent way to deal with arguments in a process is to pass them as an (string) array. This is advantageous in that you do not have to resort to unnecessary string interpolation and manipulation. It is also more readable too which is a plus in this problem setting.
A decent way to deal with output is to use a listener/event based model. This way, you respond appropriately to the events instead of having if blocks for stderr and stdout. Again, this makes things readable and let's you handle output in a more maintainable manner.
If you go a bit further into this, you will also have to solve a problem of how to inject environment variables into your target program. As an example, you might want to run the java with a debugger or with less memory in the future, so your solution would also need to cater for this.
This is just one way of solving this kind of problem. If node is your platform, then have a look at Child Process which supports all of these techniques.
We can run the whole java project by making .jar file of it and run it using the command in the shell and run that shell file. In order to run java code from nodejs project as we know project could be a mix of java, js modules.
Call exec() function in node to create a child process to execute the shell file having a command to run .sh file and can also pass some argument in it from use.eg;
let fileName = 'someFile.txt';
let userName = 'Charlie Angle';
exec(`sh run.sh --context_param
paramFilePath="./storage/${fileName}" --context_param userName="${userName}"`, (error, stdout, stderr) => {// Some code based on execution of above command})
You can simply call a java command , with classpath & arguments, using module node-java-caller, it embeds the call to spawn and will also automatically install java if not present on the system
https://github.com/nvuillam/node-java-caller
I would like to "link" few file extensions to my java application under windows. When user double clicks file with "linked" extension, I would like to open my app and I need to know path to file that launched app.
If you deploy the app. using Java Web Start, an interest in file-types can be declared in the launch file. See the demo. of the file services, which..
..prompts the user to associate file extension .zzz (simply a file type unlikely to clash with existing file associations) of content type text/sleepytime. ..
When the user double clicks a .zzz file, it should open in the app. Actually, the word 'prompts' there is not the whole story. If you launch the sand-boxed version you will be prompted as to associating the file-type. The trusted version does not prompt.
To add more user-control to the process, look to the IntegrationService that was introduced in 1.6.0_18 (I don't have a demo. of that one yet). You might run it at start-up, after checking with the user.
this would have to be done during installation. how are you planning on letting your user install your application?
you have to realize at this stage that you just made things a whole lot more complicated. registering file extensions means meddling with the registry. what happens if the user doesn't want your application anymore? or moves the file that launches your application?
you'll have to pick an installation creator. here's a so question about that: https://stackoverflow.com/questions/3767/what-is-the-best-choice-for-building-windows-installers
and then you'll have to learn that installer creator's language. here's how what you're asking for is done in nsis. remember that the script takes care of questions like "if the user uninstalls my application, and i didn't change the file associations at install time, should i then remove these file associations on uninstall?" so it's a bit long. here it is anyways: http://nsis.sourceforge.net/File_Association
maybe it can be done in an easier way in another installer creator.
however, in this example, you give the register function of nsis the start command for your application, and then it adds %1 to it in the start command of the windows file association. so you should give it the start command
javaw -cp installpath\yourcode.jar package.name.MainClassName
and then things should work out. this will take some experimenting of course, and you will have to be quite sure about how to start your application from the command line.
good luck!
Is there an easy way of passing Linux/Unix commands to Java's args[] during program execution? I would like to use Java app with cron.
The JVM already does that for you:
public static int main(String args[]) {...
In args[] you will have the command line arguments.
If you want more sofistication (as named parameters, v.g. -title = MyTitle), you can try Apache Command Line Interface(CLI) library.
EDIT to answer featon's comment: That will not work, the OS will interpret it as a call to launch a new process. Also, the process name of all java processes is "java" (the OS runs the JVM and does not know what it does in inside).
If what you want is to communicate with a Java process already running, you must open a communication path. Two alternatives are:
Open a TCP port, launch another application (Java or not) that sends the message there.
Have the process periodically listing a directory, if any new file appears wait a while (so it is fully created), open it, read it and delete it.
Another path is getting to use J2EE application server that implement functionalities more oriented to Java process that run continuously (even equivalents to cron tasks), but they take some effort to become familiar with.
If you have command or two pass it within String[] arguments. If you got more commands, consider putting them in some file and only pass the path to that file as a java program argument.
During development (and for debugging) it is very useful to run a Java class' public static void main(String[] argv) method directly from inside Eclipse (using the Run As context menu).
Is there a similarily quick way to specify command line parameters for the run?
What I do now is go to the "Run Dialog", click through the various settings to the tab where I can specify VM and program arguments and enter them there.
Too many steps, plus I do not want to mix the more permanent runtime configuration settings with the one-off invokation parameters.
What I want instead is to check a box somewhere (or have a separate menu item "Run as Java application with command line") and then be prompted for the commandline every time (with a nice history).
This answer is based on Eclipse 3.4, but should work in older versions of Eclipse.
When selecting Run As..., go into the run configurations.
On the Arguments tab of your Java run configuration, configure the variable ${string_prompt} to appear (you can click variables to get it, or copy that to set it directly).
Every time you use that run configuration (name it well so you have it for later), you will be prompted for the command line arguments.
Uri is wrong, there is a way to add parameters to main method in Eclipse directly, however the parameters won't be very flexible (some dynamic parameters are allowed). Here's what you need to do:
Run your class once as is.
Go to Run -> Run configurations...
From the lefthand list, select your class from the list under Java Application or by typing its name to filter box.
Select Arguments tab and write your arguments to Program arguments box. Just in case it isn't clear, they're whitespace-separated so "a b c" (without quotes) would mean you'd pass arguments a, b and c to your program.
Run your class again just like in step 1.
I do however recommend using JUnit/wrapper class just like Uri did say since that way you get a lot better control over the actual parameters than by doing this.
If have spaces within your string argument, do the following:
Run > Run Configurations > Java Application > Arguments > Program arguments
Enclose your string argument with quotes
Separate each argument by space or new line
AFAIK there isn't a built-in mechanism in Eclipse for this.
The closest you can get is to create a wrapper that prompts you for these values and invokes the (hardcoded) main. You then get you execution history as long as you don't clear terminated processes. Two variations on this are either to use JUNit, or to use injection or parameter so that your wrapper always connects to the correct class for its main.
I'm not sure what your uses are, but I find it convenient that usually I use no more than several command line parameters, so each of those scenarios gets one run configuration, and I just pick the one I want from the Run History.
The feature you are suggesting seems a bit of an overkill, IMO.
Another idea:
Place all your parameters in a properties file (one parameter = one property in this file), then in your main method, load this file (using Properties.load(*fileInputStream*)).
So if you want to modify one argument, you will just need to edit your args.properties file, and launch your application without more steps to do...
Of course, this is only for development purposes, but can be really helpfull if you have to change your arguments often...
This is a followup question to one I previously asked:
start-program-if-not-already-running-in-java
I didn't get a great solution there (as there doesn't appear to be one), but I have a related question:
Is there anyway to launch an application in Java code (an .exe in Windows, not a Java app) and have it start minimized? Or perhaps to minimize it right after start? That would solve the focus issue from the other question and the already running problem would more or less deal with itself.
Clarification issues again: the Java client and the .exe are running in Windows and I really don't have the ability to write any wrappers or make use of JNI mojo or anything like that. I more or less need a pure Java solution.
Again, thanks for the help and I am more than willing to accept an answer that is simply: "This is just not possible."
Windows only:
public class StartWindowMinimized {
public static void main(String[] args) throws IOException {
if (args.length != 1) {
System.err
.println("Expected: one argument; the command to launch minimized");
}
String cmd = "cmd.exe /C START /MIN ";
Runtime.getRuntime().exec(cmd + args[0]);
}
}
Sample usage:
java -cp . StartWindowMinimized notepad.exe
java -cp . StartWindowMinimized cmd.exe
To understand the arguments involved:
cmd /?
START /?
I'm not that familiar with the specifics of Java, but according to a web site I just looked at, if you're using java.awt.Frame (which includes JFrame from Swing), you should use the function off of that frame called setState, which accepts Frame.ICONIFIED and Frame.NORMAL as a parameter (iconified would be the minimized state).
How do I minimize a Java application window?
If these apps have command-line switches to make them start minimized, then you can easily use those. Otherwise, I can't be 100% sure, but I highly doubt this is possible. You would have to have some way to interface with the Windows window manager, which is inherently very platform-specific and Java is therefore unlikely to include it. It's always possible that someone has written a third-party library to handle the task but it just doesn't seem likely to me.