How to Read file from a shared location Windows? (Java) - java

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.

Related

How to access outside file from java jar

I have a jar that is reading a file using below code:
Thread.currentThread().getContextClassLoader().getResource(fileName);
I want to run this jar using java -jar .jar command but I want to keep this file outside my jar, so that I can edit the jar file later on without touching the jar. Can anyone help me, how to run this jar so that it will pick up the file from outside.
There are multiple approaches you can do that and it will depend on where would you like to place this external file. For the sake of this answer, I will refer to this file as config file
Not In The Same Directory
The first approach is where you will need to place this file outside the JAR and not necessarily next to the JAR file in the same directory. In that case, you can pass the file location of the config file using either an environment variable (if you are running the JAR in a shell for example) or a Java property.
To use an environment variable, assuming you are using some Linux distro, then you can use the export command to set the value; something like this:
$ export CONFIG_FILE_LOC=/etc/myapp/config.file
You can then read the value in your code using the System class by using the following code:
String fileLocationEnv = System.getenv("CONFIG_FILE_LOC");
Alternatively, you can set this as a property by adding the following segment to your launch command:
$ java -Dconfig.file.location=/etc/myapp/config.file -jar myapp.jar
You can then read the value in your code using the System class for properties using the following code:
String fileLocationProp = System.getProperty("config.file.location");
In The Same Directory
If you need the config file to co-exist in the same directory as your JAR file, then you can use the following code to get the JAR directory and then append the filename to it. Here's the code (assuming a class named MyApp)
try{
new File(MyApp.class.getProtectionDomain().getCodeSource().getLocation().toURI());
} catch(URISyntaxException exception){
System.out.println("Exception");
}
Hope that helps.
To open the file as a resoure, add the folder containing the file(s) you want to use, to your classpath:
java -classpath .;config -jar myjar.jar
This example adds the current directory and the config directory to your classpath.
Multiple folders can be specified by using a separator. On windows use ';' , on unix use ':' .
To open the file as a File, you can just use
new File("configfile")
which will look in the working directory (directory where you launched your java)

Can we use windows bat file in Java jar file, so that java can run some windows command, if yes where we should keep bat file in side that jar file

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.

How can I find a file while in my java code

I am stuck on a how to robustly find a file path from my Java program. If I am using Linux, I can launch my program from my home folder, and then I can't say find my file at ./myProgram/myFile. Is there a good way to find my file no matter what directory my console is in?
If you are trying to access the file using the path:
./myProgram/myFile
in your program, but you aren't executing the program from the myProgram directory, then you're Java code won't see the file. Try providing it with the full path instead of the relative path. If myProgram is a directory found in your user's Documents directory then a full path would likely look something like this:
/home/*username*/Documents/myProgram/myFile
You could also build in functionality that lets you select the file by navigating through the directories and listing the files. The would provide the user with options to choose which file to utilize in the program.
You can just as well cd to the myProgram directory before executing the file and then the relative path ./myProgram/myFile should work.
Hope that helps.
Try this:
File f = new File(System.getProperty("user.home") + System.getProperty("file.separator") + "myFile.txt");

Calling a path in java method

I have a small problem calling a path(that has the python file, that I need to run) in the following code:
Process p = Runtime.getRuntime().exec(callAndArgs,env,
new java.io.File("C:\\Users\\Balkishore\\Documents\\NetBeansProjects\\Testinstrument_Rest\\build\\web"));//excuting python file
As it can be seen from the above code, the python file is called using the path specified in java.io.file function. But it is very specific, as it can be run only in my computer. How can i make it generic, so that it is possible to run this piece of code in any computer?
Any help would be very much appreciated.
Put your python script to the location relative to your working directory and use relative path. Alternatively use configuration file or property to read the path from.
If this file is already exist in the app then you need to do
ServletContext.getRealPath("/");
which will give you the path to web root now from here you need to move relatively to reach to your file
If this is an external file
put it in ${user.home}/appname/
String filePath = System.getProperty("user.home")+File.separator+"APP_NAME"
and instruct your users to put the file in this path, or read the path from some configuration file (.properties, .conf)

Best to way execute a file internal to a java project

Suppose my project structure is:
/project
/src
/java
Util.java
/cpp
/bin
a.out
I'd like to execute a.out from within Util.java without hard-coding any absolute paths in my java file. What's the best way to go about doing this?
EDIT -- Here's what I ended up doing: I happen to be using autoconf as most of the code is c++. I defined a substitution variable like AC_SUBST([project_root], [$(pwd)]) in configure.ac and substituted it in a Config.java.in file.
Perhaps using a properties file to be loaded on deployment/running time depending on the nature of your app.
More about its use in this thread
How to use Java property files?
You're file path to a.out could be ../bin/a.out. And then execute the file using that path.
Below is some pseudo code that might help you.
// look for the executable in the current working directory
File executable = new File("a.out");
if( executable.exists()){
System.exec() .... etc
} else {
String location = YourMainClass.class.getProtectionDomain().getCodeSource().getLocation();
// write code to form a path name to the a.out based on the location of .jar file
}

Categories

Resources