i tried to run an exe file from the same package the program is in using
Process p = Runtime.getRuntime().exec("prog.exe");
and
Desktop.getDesktop().open(new File("prog.exe"));
but they both give me errors. I made sure there was no spelling error in the name and it still gave me an error. is there another way to do this without having to use the entire directory?
You need to copy it from the resource which might be in a jar to an absolute path. Also make sure to get the path correct. If prog.exe is in the same directory a class in package pkg, then you need to add pkg/ to the resource name.
File tmpCopy = File.createTempFile("prog", ".exe");
Files.copy(ClassLoader.getSystemResourceAsStream("pkg/prog.exe"), tmpCopy.toPath(), StandardCopyOption.REPLACE_EXISTING);
// Needed on Linux/Mac only ---Files.setPosixFilePermissions(tmpCopy.toPath(), PosixFilePermissions.fromString("rwxrwxrwx"));
Process p = new ProcessBuilder(tmpCopy.getAbsolutePath()).inheritIO().start();
p.waitFor();
Related
I have created a .txt file in my Eclipse Java project, and I want to find out the path to it so I can use it for a Scanner. I do not want to find out the path on my local drive, as I will be planning to share the program to someone else, and they will have a different folder structure, rather a path that can be used on anybodies machine.
Here is the code:
this.file = new File("<insert path here>");
you can use :
= new File("Build Path"); (your .java file exist in your build path)
The build path is used for building your application. It contains all of your source files and all Java libraries that are required to compile the application.
In eclipse, the default behavior is for the Java system property user.dir to be set to the project directory. This is what dictates where the "root" of File operations is. So if you created a file test.txt in the root project directory, you should be able to access it with new File("test.txt").
However, as Andrew Thompson mentioned in his comment, the more correct method would be using embedded resources.
Try one of These:
1.
System.getProperty("user.dir");
2.
File currentDirFile = new File(".");
String helper = currentDirFile.getAbsolutePath();
String currentDir = helper.substring(0, helper.length() - currentDirFile.getCanonicalPath().length());//this line may need a try-catch
I have not tested it just found while googling
I am trying to execute a windows command inside java code using Runtime.exec() command. It is working fine when put all the necessary batch file and properties file on the root directory. But when i am exporting this is as jar, the java program is throwing error, which is becuase it is not able to find all those dependent .bat and .properties files. Can some one please tell me, where should i keep all the .bat and .properties files in side the folder. Thanks in Advance.
You can do so
Something like
Runtime.getRuntime().exec("cmd /c start yourFile.bat");
You should be able to keep it in the root of your jar if you want
EDIT :
On second thought I don't think you can run bat files inside a JAR
you would have to extract it and then run it
Please give more information on what it is you want the bat file to be doing and I can update this answer maybe there is another way?
Your problem can be divided into two parts: get the bat from the jarand run it.
To get the bat from the jar, you will have to use the ClassLoader to get a resource. you can achieve this by using the method Class.getResource to get the URL or Class.getResourceAsStream to get an InputStream
Anyway, i dont' think you can run the bat from inside the jar. If you try and fail, my advice is to create a temp file, copy your bat into your temp file and run that file.
P.S: Class.getResource finds file in the classpath. If your file is not in your classpath, you won't be able to find it this way.
EDIT: i add the code i'm using to get resources from a general relative path, given the path exist both starting from you working directory and from the home of your jar. It works, i've been able to just pack every folder i need into the jar and ship the jar to another compute rwhere eveything worked fine.
public static URL getResource(String name) {
if ("jar".equals(Main.class.getResource("Main.class").getProtocol())) {
return Main.class.getResource(("\\" + name).replace('\\', '/'));
} else {
try {
return (new File(System.getProperty("user.dir") + "\\" + name)).toURI().toURL();
} catch (MalformedURLException ex) {
return null;
}
}
}
Main is a known class, in this case the class where this static method is. I first use it to get a known url, and see if i am executing from a jar. If i am, i use the getResource, otherwise i use the File api.
the structure i use is this
main_folder\
res\
src\
package\
and, in the jar
file.jar\
package\
res\
and i need to use both File api and getResource since in the rist case the res folder is not in my classpath. with a different structure probably only the getResource method is fine.
This should solve your problem of getting the bat file, you still need to see if you are able to run it, and if you are not, copy everything into a temp file and run the temp file instead.
Hopefully this will make some sense. I'm new to Java and while I've built .jar artifacts before, I have never had to build a program that takes another file as input. I'm running into a weird problem and I'm not sure how to fix it.
Basically, I have a Main.java class that calls a .txt file and passes it to another class, myClass.java. I generated a .jar file with IntelliJ, which inserted itself inside its own folder.
To make things easier, here is the basic structure of my program.
/src
/com.myProgram
Main.java
input.txt
MyClass.java
/out
/artifacts
/myProgram_jar
myProgram.jar
And here is a basic version of what's in Main.java
myClass mc = new myClass("input.txt");
I tried running the .jar file with the command "java -jar myProgram.jar", and I get the error "The system cannot find the path specified". I ran getCanonicalPath() on input.txt. Apparently my program is looking for input.txt in out/artifacts/myProgram_jar instead of in the src/ folder.
What can I do? Even when I put the full path to force the program to look in the src/ folder, it will still attempt to look in the myProgram_jar folder and throw an error. So I cannot execute the file at all. Any suggestions for solving this error are greatly appreciated!
When you build to jar file, it's not a File anymore. A File is only a physical file on the file ystem.
So have 2 way to fix it:
1. You export the txt file to system as D:/New folder, then you get this file with path of this file.
2. You can try this:
try {
URL url = new URL(this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI().toString()+your path to file in structre);
InputStream in = url.openStream();
} catch (URISyntaxException ex) {
Logger.getLogger(PrepareGUI.class.getName()).log(Level.SEVERE, null, ex);
}
I am using the below code to access and run a bat file
Runtime runtime = Runtime.getRuntime();
Process p =null;
p = runtime.exec("cmd /c c:/{foldername}/codereview.bat");
I realized that my code is not portable as i have hardcoded the path, so i copied my bat file in a folder under /src and am now trying to use it after removing the c:/{foldername} part but
the code is not working for me... The file can not be found.
Please help as to how i can provide the relative path inside the bat file.
I did not get your exact problem but I think this may help you:
To get the absolute path of your source program(the class file executing) use this:
String path = System.getProperty("user.dir");
Now you can dynamically the path of your program and the hence the batch file(which I think is relative to the class file)
Is there a way to read a file from a network shared location on windows?
Let's say for instance I've this simple code that reads a text file called readMe.txt from the Addons folder.
import java.io.File;
class Sample{
public static void main(String[] ar){
File file = new File("Addons/ReadMe.txt");
System.out.println(file.getAbsolutePath());
//followed by printing the contents of file
}
}
And I execute this file using a windows batch runme.bat that has
java Sample
PAUSE
The bat runs and executes the above class only when I place the Addons folder with ReadMe.txt, Sample.class, runme.bat file in my local drive.
When it is placed in a network shared location with UNC path like \\name\Shared
In such a scenario, the bat file typically starts the base from C:\Windows and throws a classNotFoundException. I can rather map the shared drive to a *Z:* drive or whatever but I do not want to do it.
I want the code to programatically detect and retrieve the content of Readme.txt in Addons folder irrespective of whether it is being executed on a local drive or on a shared drive. Is there a way to achieve this? Please help..
Thanks
Veekay
When using a file path in Java, make sure to escape all \ correctly when giving the full path name.
For example, if the file is on PC with IP (10.10.10.123) on a Shared folder called Addons then the full path will be:
File f = new File ("\\\\10.10.10.123\\Addons\\readme.txt");
Other than the full path, your code is throwing a ClassNotFound because you JAVA-CLASSPATH is not set properly.
In your bat file %~dp0 expands to the location of the bat file. You need that in your classpath so that java can find the class, though I don't know if it will choke on UNC path. For example:
#echo off
echo %~dp0
would output
\\host\share\dir
EDIT: %dp0 will not work if there are spaces. This is what you need in your bat file:
#echo off
set p=%~dps0
echo %p%
java -classpath %p%\jarname classname
pause
Two ways of doing.
1) Map the shared path to a local drive.
2) Else hard code the server path in new File('') as mentioned by Medopal.
Something like new File("").getAbsolutePath() might help me get the base Folder when executed on a local system. Likewise there is no such way to programmatically find out the working base when executed on a shared location.