How can i implement opening a file with my java program? - java

I have a basic, simple and maybe stupid question, but how do I implement that I can drag a file onto my java program and open it?
I searched really long for this basic question.....
As long as I found out you can't implement dragging it onto the .jar, because its not executable. You have to create a .exe, which also open your .jar, but that's all! I would really like to know how :)
A keyword would be enough, if I can get the answer through searching this keyword.
Thanks, Leander
//Edit: I may have expressed things a little bit complicated.
Later i want to have a shortcut on, for example, the desktop where i can drag any file on the shortcut and the programm opens with the file(it will, at this point) only move it to a special location.
I donĀ“t know how the code for this would be, I even don't know how to google for this (I only get questions how to implement "open with" with the answer Desktop.open(File f)).

For windows only:
option 1:
make a batch file into the directory of your jar file (or anywhere you like but then you need to adjust the path, you can also make a shortcut from the batch file).
#ECHO OFF
start java -jar %~dp0MYAPP.jar %1
option 2:
Make a shortcut (right click - new - shortcut)
Enter into the location "java -jar C:\path\to\myapp.jar"
drag and drop will work if your jar accepts filename as a parameter
public class Main {
public static void main(String[] args) {
if (args.length == 0)
System.out.println("No arguments");
else
System.out.println("1st argument: " + args[0]);
}
}

The place to start reading is the JDK 6 documentation on Drag and Drop. Or else you can start directly with the Drag and Drop tutorials.
If you want to create a desktop icon that will open your app when you drop a file on it, this depends on the OS. I think that Launch4j will support this, although I haven't used it in this way.

On window you can create .bat file, and if you DnD on that file you get filename as fisrt parameter
so code
echo %1
pause
writes the filename out, so you can start you java program like
java -jar myApp.jar MyAppClass %1

Related

Open external .jar with Runtime.getRuntime().exec with java

So I have this code that works fine, it launch the .jar file from another machine that I have configure in my pc as a red ubication
Runtime.getRuntime().exec("java -jar Z:\\AAA\\BBB\\CCC\\ZZZ.jar");
But now I want to launch the .jar from that external path without using the shortcut before (so I can launch it with this code in a machine that dont have that red ubication configured)
Runtime.getRuntime().exec("java -jar MMM\\NNN LLL\\OOO\\AAA\\BBB\\CCC\\ZZZ.jar");
But doent work (I can access and open the file manually without a problem).
When I enter the java -jar MMM\\NNN LLL\\OOO\\AAA\\BBB\\CCC\\ZZZ.jar in the Command prompt it return me Error: Unable to access jarfile MMM\NNN, so perhaps one problem is that the path have a space in the folder name, but I think that may be something else too.
The question is, if the problem is the space, how I can solve it? I cant find a way. And in the other hand, how I can run it in another machine? I have to use that red ubication IP in some way instead?
PD: Using this code, it return me true
File f = new File("\\\\MMM\\NNN LLL\\OOO\\ZZZ.jar");
System.out.println(f.exists()); //--> true
So looks like the spaces dont interfere in the path (the four "\" doesnt seem to do anything in the tests when launching)
I have heard other people having such problems. The main reason for that is that probably Java exec method is not network (SMB) aware. So it doesn't even try to open from the network.
Anyway running the code like that from the network might not be the best solution. First of all the network might be unavailable, or the java file coming might be corrupted. If you want to do it properly you have several options:
Simple option that can work:
Create a bat file that works and exec that one - you can even copy the file locally first to make sure it is available first (if it is big and the network fails)
A better solution :
Use java to copy the file to the working directory and execute it from there.
A plus to do it like that by downloading is that you can maintain a version of the file (hash?) so you don't download it if it is the same. Or you can have fallback - execute the last downloaded version if the network drive is unavailable.
Use a local maven repository and dependency for that jar :)
This way it will keep the version of the jar locally and won't have to download it every time. It will also download a new version if available and the code will be more mainstream (for example not platform / pc dependent)
The answer give by #MadProgrammer works fine!
ProcessBuilder builder = new ProcessBuilder("java", "-jar", "MMM\\NNN LLL\\OOO\\AAA\\BBB\\CCC\\ZZZ.jar");
try {
builder.start();
} catch (IOException e) {
e.printStackTrace();
}
Lot of thanks! In any case going to check the ideas posted by Veselin Davidov

Write a batch file that starts a java program

So I have a java project with multiple java files.
I know that is almost straight forward to start a java application using batch file. But that is for a pretty simple java program with a single class.
However I am wondering if it is possible to do that with in a scale of a project that you usually create using eclipse. A large project with multiple packages, classes and multiple java files.
My try was to write a script and apply on the main class as following
set path = C:\Program Files\Java\jdk1.7.0_25\bin
javac -classpath twitter/twitter4j-stream-3.0.5.jar;twitter4j-core-3.0.5.jar" sourcepath="lib/twitter4j-core-4.0.1.jar;lib/twitter4j-core-4.0.1.jar;lib/twitter4j-stream-4.0.1.jar;svm_light_lib Program.java
java Program
However when I start the .bat file it automatically closes.
Any Ideas ?
Thanks in advance
First, never overwrite the environment variable path, not even
temporarily. Append your folder instead: set "path=%path%;%mypath%" or set "path=%mypath%;%path%".
(There exists a particular path command but I'm not sure about right syntax: path=%path%;%mypath% with = assignment or path %path%;%mypath% without it).
Use full path to a program if you know it, e.g. "%mypath%\javac".
For better readability, values for -classpath and -sourcepath options are stored to the environment variables mycpth and mysrcp, respectively. Note and use proper " quotation and no spacing around = to avoid any leading and trailing spaces in all set commands.
pause to see all the javac output. Displays the message Press any key to continue . . .
Next code should be (syntax) error-free. However, success depends (among others) on classpath and sourcepath entries visibility as well...
set "mypath=C:\Program Files\Java\jdk1.7.0_25\bin"
set "path=%path%;%mypath%"
set "mycpth=twitter/twitter4j-stream-3.0.5.jar;twitter4j-core-3.0.5.jar"
set "mysrcp=lib/twitter4j-core-4.0.1.jar;lib/twitter4j-core-4.0.1.jar;lib/twitter4j-stream-4.0.1.jar;svm_light_lib"
"%mypath%\javac" -classpath "%mycpth%" -sourcepath "%mysrcp%" Program.java
pause
java Program
However I am wondering if it is possible to do that with in a scale of a project that you usually create using eclipse. A large project with multiple packages, classes and multiple java files.
Of course it is possible!
In this case, I suspect the problem is that you java command doesn't have a "-cp" argument. The java command is probably failing because it can't find twitter classes ... at runtime.
Remember to include "." on the classpath ... or else java won't find the file that you just compiled.
#JB Nizet's suggestion is also very important advice for finding out what is actually happening.

Java get current file name EXE

This is my first Stackoverflow question.
I searched across Google for getting the current file name in Java. Most of the sources tell users how to find the current file name if the file is a JAR file, but I'm asking for if the current file is an EXE file.
I saw one EXE answer in Get name of running Jar or Exe, but I don't think it worked.
I use the JSmooth EXE wrapper (launch4j somehow didn't work for me), and Java 8. Is there a straightforward solution to my question? Also, it's nice to explain how it works, or provide a link to the Java documentary about it.
EDIT: To clarify, let's say that I made a Java program and used a JAR wrapper, and I named the resulting EXE "test.exe". I want the Java program be able to give me the current directory of "test.exe", including the filename itself (test.exe).
ANOTHER EDIT: Just to clarify more, go onto your desktop, create a text file, and put some text in it. Save it, and change the text file to an EXE file. Then, try to open it. Windows will give an error. Notice how the title of the message dialog is the file path of the opened file. That is the type of output I want.
Thanks.
Per the JSmooth documentation,
JSmooth also makes some special variable accessible for your application.
Form Meaning
${EXECUTABLEPATH} Replaced by the path to the executable binary. For
instance, if the executable binary launched is located
at c:/program files/jsmooth/test.exe, this variable
is replaced with c:/program files/jsmooth
${EXECUTABLENAME} Replaced by the name of the executable binary. For
instance, if the executable binary launched is located
at c:/program files/jsmooth/test.exe, this variable is
replaced with test.exe
You set these in JSmooth under the "Environment Settings" (the last panel), which allows you to map the variable name. So,
MY_EXECUTABLEPATH=${EXECUTABLEPATH}
MY_EXECUTABLENAME=${EXECUTABLENAME}
In your application, you can get those with
String execPath = System.getProperty("MY_EXECUTABLEPATH");
String execName = System.getProperty("MY_EXECUTABLENAME");
public class JavaApplication1 {
public static void main(String[] args) {
System.out.println("Working Directory = " +
System.getProperty("user.dir"));
}
}
This will print a complete absolute path from where your application has initialized. It is used to get only the DIRECTORY.
If you are using a .exe why do you not create a installer? You can use Inno Setup, this way you are able to specify where do you want to store your .exe, and get it from your application just passing your custom directory

How do Jar files work when using runtime.getRuntime().exec() [duplicate]

This question already has answers here:
Can I set Java max heap size for running from a jar file?
(8 answers)
Closed 9 years ago.
I am trying to create a jar file that will execute my game with just a click. My game exceeds java's default allocated heap memory so I have to run my code with -Xmx1000m. I've been researching online and unfortunately there doesn't seem to be a way to tell a jar file to fun my code with more than the default memory. Instead I created another class that will use runtime to compile my code from within another main method and created a jar file using this:
import java.io.*;
public class RuntimeExec{
public static void main(String[] args){
try
{
Process process = Runtime.getRuntime().exec("java -Xmx1000m Controller");
process.waitFor();
int exitCode = process.exitValue();
if(exitCode == 0) { /* success*/ }
else { /*failed*/ }
}
catch (Exception e)
{e.printStackTrace();}
}
}
This works however I think it only works because it runs my existing class in the folder and not the one I stored in the jar. Is there a way so that the jar will run a class within in or combine two different jars that will allow me to get around the memory heap problem?
The entire solution to providing an easy install for users is to deploy the app. using Java Web Start. It can set RAM for an app., and also install a desktop shortcut to launch it. JWS is much more robust than a (poorly implemented) call to exec.
However if JWS is not for some reason suitable for this app., see IWantToBeBig for a hack that will cause a Jar to have enough memory (similar to how you use exec above, but slightly more robust in using ProcessBuilder to relaunch the app. that does not have enough memory).
Organizing the desktop shortcut to allow the user to launch it with a click, is left as an exercise for the reader.
There are many ways of doing it:
As you mentioned, by having another Jar file which triggers your game file
As #Perception mentioned, have a batch file which will start your game. But be careful, if downloaded from say Net, the user will have to set permissions for the script to be runnable
Build an installer. On Mac, using the Oracle Java App bundler for Java 7, Apple App bundler for Java 6 build the .app file. You still cant redistribute it as the necessary permissions wont be set. Build a dmg for the app file. This can be used for distribution.
A similar installer for Windows
The third technique would be the best, as you can then package the dependencies well, set all JVM arguments etc

Java Eclipse executable jar file

I am new to eclipse + Java. I am trying to create executable jar file with eclipse
export option. It works very well. But in my project, I have almost 10 packages (my own) and 4 main classes. I want to create a executable jar file that can execute any of main class from 4 main classes.
For example: Double click write class name and run that class
Dont use executable jar. Instead create a normal jar which will have compiled classes.
From command line, call whichever main class you want to call as a argument to the java jar command.
java -jar test.jar com.company.unit.MainClass1
java -jar test.jar com.company.unit.MainClass2
Executable JARs don't work that way. They write a manifest file in the JAR that declares where the main class is, and it runs that one. You would have to create 4 different JARs.
Alternatively, you can just create one main class that lets you type in which of the four you want, and then have it execute that one. Basically, you'd be mimicking the functionality that you are looking for on your own.
Just a quick example of how to deal with command line options to launch different things, I would have put it into a reply to #serplat's answer but then I can't format it.
public static void main(String[] args)
{
if(args.length == 0) {
// Do default here--no options specified
} else if(args.length > 2) {
// Complain that there are too many args, or implement multi-args
} else // known just one arg
if(args[1].equals("option1") {
// call the main of your first app
} else if(args[1].equals("option2") {
// start your second app
...
}
}
There are much better ways to handle command line stuff, but this is understandable and should do what you need. Later you might look into something more flexible.
I have recently made a tutorial that shows you how to create an executable jar file that will run with a double click in Windows, Mac OSX and Linux. For my project, I packaged a slick library game I had made. Hope it helps.
http://aramk.com/blog/2010/12/05/how-to-make-a-multi-platform-executable-java-jar-file/

Categories

Resources