how to open a file in a .jar through java - java

I want to open a file in .jar application and I want to use java to do this. Explaining, for example I have the file SF_Antivalent.xml and I want to open it with uppaal.jar. How do I do this using Java. I've written the following code, but it doesn't work.
public class test7 {
public static void main(String[] args){
Runtime rt=Runtime.getRuntime();
String file="C:\\Users\\V\\Documents\\diplwmatiki\\SFBs\\SF_Antivalent.xml";
Process p=rt("C:\\Windows\\System32\\java.exe", "-jar", "C:\\Users\\"
+ "V\\Documents\\uppaal-4.0.13-aca\\uppaal-4.0.13\\uppaal.jar" + file);
}
}
and I get this error: the method rt(String, String, String) is undefined for the type test.
Is there something to do?

You question is a little confusing, however, I believe you want to run some application and pass the XML file as a parameter to it...
The problem is, you're treating rt as a function/method, not an object. Runtime has the an exec method used to execute external commands, for example...
Runtime rt=Runtime.getRuntime();
String file="C:\\Users\\V\\Documents\\diplwmatiki\\SFBs\\SF_Antivalent.xml";
Process p=rt.exec(new String[]{
"C:\\Windows\\System32\\java.exe",
"-jar",
"C:\\Users\\V\\Documents\\uppaal-4.0.13-aca\\uppaal-4.0.13\\uppaal.jar",
file});
Also, each command or argument you want to send to this external process must be it's own element within the array you pass to this method
This means tha "V\\Documents\\uppaal-4.0.13-aca\\uppaal-4.0.13\\uppaal.jar" + file won't actually have the effect you think it will.
I'd also recommend that you use ProcessBuilder over Runtime#exec, but that's me.

The reason you are getting the error is because rt is a Runtime object, not a method. To call a method of rt do this:
rt.someMethodName();

With the code above you cannot get XML file, you're trying to execute something, instead of opening file inside JAR archive
Look into getResourceAsStream, this will give you possibility to load any file from JAR

Related

How to provide the -Dlogback.configurationFile=./logback.xml option in nodejs spawn method

I have angular2-node.js application. I am executing a jar file through the node server.
Jar execution is happening fine but it's using the logback.xml present in the jar file.
Node js code:
app.get('/report/:parameter1/:parameter2', function(req, res) {
var fileName = path.join(__dirname, '..', 'javaFile', 'xyz.jar');
spawn('/usr/bin/java', ['-jar ', fileName, parameter1 , parameter2, '&'],{
stdio : ['ignore', out, err],
detached : true }).unref();
data = '{response: Success}';
res.status(200).json(data);
res.end();
});
I want to refer the different logback.xml file for jar execution while running the jar from UI. So, i tried the below code:
spawn('/usr/bin/java', ['-jar -Dlogback.configurationFile=./logback.xml', fileName, cacheName , cacheType, '&'],{
stdio : ['ignore', out, err],
detached : true }).unref();
But, it also didn't work and throw the below error:
Unrecognized option: -jar -Dlogback.configurationFile=./logback.xml
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
I am new to node js. I searched the web but couldn't get an answer.
Is there any way to provide the logback.xml file dynamically in node.js code something like we do in shell script like below:
nohup java -jar -Dlogback.configurationFile=./logback.xml xyz.jar
Can anyone provide any solution for this.
The args arguments is <string[]>, so you should split the multiple args into multiple elements of the array, like you've done for the other arguments. You can check the signature of the method here.
Try,
spawn('/usr/bin/java', ['-jar', '-Dlogback.configurationFile=./logback.xml'], ....

Java ProcessBuilder redirectInput with cat

I am writing a Java application that needs to execute the unix cat command using ProcessBuilder. I know I can use the arguments to the ProcessBuilder object to specify the file for cat to use. However, to standardize the interface, how would I use redirectInput() instead to pass the input file?
I'm assuming this would work as I can perform cat < foo.txt in the command line, which is equivalent to redirectInput() in ProcessBuilder (right?)
Help is much appreciated :)
Why not just try it?
I've written a simple test code:
new ProcessBuilder("cat")
.redirectInput(new File("/tmp/test", "i.txt"))
.redirectOutput(new File("/tmp/test", "o.txt"))
.start()
.waitFor();
And it successfully copied some text from i.txt to o.txt.

Cloning java application on Windows

I am trying to start a new process with Runtime.exec() from my javafx application.
The new process is my javafx application (but in a new process, the "parent" one will still be open).
So I run javaw via the exec method and tell it my classpath. And here is my problem: the classpath contains whitespaces, so I need to quote every path. But I retrieve the path at runtime via java.class.path (since it is the same application).
Do I need to process the string and quote everything or is there an easy way to get this to work?
Here is the code:
public static void startInNewProcess() {
try {
Runtime r = Runtime.getRuntime();
File javaPath = new File(System.getProperty("java.home"), "bin/javaw");
File classPath = new File(System.getProperty("java.class.path"));
System.out.println("java loc: " + javaPath.toString());
System.out.println("classpath: " + classPath);
Process p = r.exec(javaPath.toString() + " -classpath " + classPath.getPath());
} catch (Exception e) {
e.printStackTrace();
}
}
I get the following string as classpath:
classpath: C:\Users\kwilhelm\git\ResourcePlaner\bin;C:\Program Files (x86)\eclipse\plugins\org.eclipse.fx.ide.css.jfx8_2.0.0.201506111511.jar;C:\Users\kwilhelm\git\ResourcePlaner\lib\itextpdf-5.5.6-javadoc.jar;C:\Users\kwilhelm\git\ResourcePlaner\lib\itextpdf-5.5.6-sources.jar;C:\Users\kwilhelm\git\ResourcePlaner\lib\itextpdf-5.5.6.jar;C:\Users\kwilhelm\git\ResourcePlaner\lib\controlsfx-8.40.9.jar
But javaw gives the error that it can't find mainclass "Files", so it can't handle the whitespace in the path.
So is there a way to get the classpath with quotes?
Is there a better solution?
Any help is apreciated
And here is my problem: the classpath contains whitespaces, so I need to quote every path.
Actually, no you don't.
And in fact, if you do attempt to quote every path, it is likely to mess up bigtime, because exec doesn't understand shell quoting.
What you actually need to do is this:
Process p = r.exec(new String[] {javaPath.toString(),
"-classpath",
classPath.getPath()});
This tells exec exactly where the boundaries of the command arguments are, so that it doesn't need to try (and fail) to figure it out for itself.
In fact, that still isn't right. You also need to add:
any other JVM options that the cloned instance needs,
a class name, and
any arguments required after the classname.
The classname is mandatory. (You left it out, and that is why the java command was outputting its help message!)

Getting "class does not have a static void main method accepting String[]" error even though main signature is correct

My DrJava was working fine, but now I keep getting the folowing error whenever I run anything:
Static Error: This class does not have a static void main method accepting String[].
So it will compile OK, but then it shoots out the error . This happens even though everything I test does indeed have a public static void main(String[] args) in it. It seems like a classpath/resources type of error. I appreciate any tips
EDIT: my class
public class Test{
public static void main(String[] args){
System.out.println(" hashmap ");
}
}
There's nothing wrong with the code, so the problem must be with the environment.
Check that you're actually executing that class. Find out where the class that's executed is specified and check it's correct
Check that you're compiling the class. Maybe the code you're looking at has not been compiled and you're trying to execute an old version that was compild before you coded a main()
Check your classpath. Is the compiled class accessible in the classpath of the java command
You don't need to reinstall java, nor is it a java version issue. It may be the way that your are running the program.
To check if it is a problem with your code, do the following:
Make a new folder and put Test.java in it.
Open up Command Line Or Terminal and change to that folder .
Type javac Test.java. Test.class should be in the folder now.
If you want, open up the class with a text editor. This is what I get:
˛∫æ2
<init>()VCodeLineNumberTablemain([Ljava/lang/String;)V
SourceFile Test.java hashmap Testjava/lang/Objectjava/lang/SystemoutLjava/io/PrintStream;java/io/PrintStreamprintln(Ljava/l ang/String;)V! *∑±
% ≤∂±
Back to the command line or terminal, type java Test.
If you get an error, which you shouldn't, I don't know what to say. It should produce the string " hashmap " on to the command line or terminal.
Why re-installing Dr. Java may not work is because you may be using the same working directory, causing same run settings to be used. Dr. Java may be running an external program, one without a main method.
I think that you should install the Eclipse IDE for Java. It is much easier to get around, it looks nicer, and it runs the file or project that you are looking at currently.
Sometimes this problem happens because may be mistake in saving file.you always your file using double quotes and with the .java extension which is main class means that class containing main method.
you should save your file by class name which is public .if there is two classes and both have main method then you should save your file by class name that is public and that class will be run.As like your compiler looking for main method in public static void main(String [] args) that is contract for jvm to run a programme
so it is not able to found that main method that is static and it looking for your Dr class.java
See this Example it have two main methods and practice these kinds of question.I also got this kind of problem in starting.
public class TestFirst
{
public static void main(String [] args){
System.out.println(" TestFirst ");
}
}
class Test{
public static void main(String [] args){
System.out.println(" hashmap ");
}
}
if you save pro-gramme by "TestFirst.java" then o/p will come TestFirst if you do some mistake in main method because we have saved our programme by TestFirst then you will get error like you got.
# 2nd mistake may be this
debian#debian:~/Geany_java$ javac Test1.java
debian#debian:~/Geany_java$ java Test1
Exception in thread "main" java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(StringTokenizer.java:349)
at Test1.main(Test1.java:11)
your classpath has not set properly See above Compiling successfully but running showing same kind of error you got.Which OS is using I can guide you properly.
Check that actually your file have the .java termination nor the .dj
There is nothing wrong with the code.
It is the executing environment which might have problem. Please share the details.
Check if program compiled correctly.
Check time-stamo of .class file.
Check permissions on folder/directory where class-files are getting generated.
Check if DrJAVA has appropriate permission on the directory.
Did you create a file, compiled it with out main?
Check class-path. Might be possible that previous class file is still being found by JDK in classpath.
Try compiling .java file from cmdLine instead of editor.
As others have mentioned, your code is fine. There must be a problem with your environment. I recently experienced a similar issue when investigating and answering this question.
Basically, in that question, the code Void.class instanceof Class resulted in a compiler error because a user-made Class.class existed in the classpath, so one Class (the Java built-in java.lang.Class) didn't match with the given Class (user-made).
Something similar may be at work here. It is possible that there is a user-made String.class in your classpath. Then in your main signature, String[] args would mean an array of your String, when Dr. Java must be looking for a main method taking an array of the Java built-in String, i.e. java.lang.String[]. If you have a custom String class in your classpath (or in your project?), then the Java compiler will choose it over the built-in String. If you were to compile and run your Test class from the command line, then you would get the runtime error: Exception in thread "main" java.lang.NoSuchMethodError: main.
Following #S0urceC0ded's suggestion, you may find this when looking at Test.class in a text editor:
main([LString;)V // A user-made String class
instead of what it's supposed to be:
main([Ljava/lang/String;)V // The built-in java.lang.String class
If so, remove your own String class (at least the .class file, but also the .java file so the .class file isn't re-created) from the classpath, and compile and run your Test class again.
Without a look at your environment, I can't tell for sure that this is the issue. But it can explain it.
If you are using Dr.Java as IDE, then you need to make sure that the main class containing 'public static void main' should be at the very top of your program. Otherwise Dr.Java throws this error during runtime.

Running a program from within Java code

What is the simplest way to call a program from with a piece of Java code? (The program I want to run is aiSee and it can be run from command line or from Windows GUI; and I am on Vista but the code will also be run on Linux systems).
Take a look at Process and Runtime classes. Keep in mind that what you are trying to accomplish is probably not platform independent.
Here is a little piece of code that might be helpful:
public class YourClass
{
public static void main(String args[])
throws Exception
{
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("name_of_your_application.exe");
int exitVal = proc.exitValue();
System.out.println("Process exitValue: " + exitVal);
}
}
One question in S.O. discussing similiar issues. Another one. And another one.
You can get a runtime instance using Runtime.getRuntime() and call the runtime's exec method, with the command to execute the program as an argument.
For example:
Runtime runTime = Runtime.getRuntime ();
Process proc = rt.exec("iSee.exe");
You can also capture the output of the program by using getting the InputStream from the process.
The difficulty you will run into is how to get the application to know the path. You may want to use an xml or config file, but if you use this link, it should explain how to run a file:
http://www.javacoffeebreak.com/faq/faq0030.html
You may also want to consider passing in some kind of argument to your program to facilitate finding the specific program you want to run.
This could be with command line arguments, properties files or system properties.

Categories