How to read a file from a shared Windows location? (Java)

Is there a way to read a file from a shared network location in windows?

Say, for example, I have this simple code that reads a text file 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 run this file using the windows runme.bat package which has

 java Sample PAUSE 

The bat starts and executes the above class only when I put the Addons folder with the file ReadMe.txt, Sample.class, runme.bat on my local disk.

When it is placed in a shared network attached storage with a UNC loop, for example \\ name \ Shared

In such a scenario, the bat file usually starts the base from C: \ Windows and throws a NotFoundException class exception. I can map the shared drive to * Z: * or another drive, but I don’t want to do this.

I want the code to programmatically detect and retrieve the contents of Readme.txt in the Addons folder, whether it runs on a local drive or on a shared drive. Is there any way to achieve this? Please, help..

thanks

Veekay

+4
source share
3 answers

Two ways to do it.

1) Map the shared path to the local drive.

2) Another server hard code path in a new file (''), as mentioned by Medopal.

Something like new File("").getAbsolutePath() can help me get the base folder when executed on the local system. Similarly, there is no way to programmatically search for a work base when executed in a common location.

+1
source

When using the file path in Java, make sure you select everything \ correctly by specifying the fully qualified path name.

For example, if the file is located on a PC with IP (10.10.10.123) in a shared folder named Addons , then the full path will be:

 File f = new File ("\\\\10.10.10.123\\Addons\\readme.txt"); 

Besides the full path, your code throws ClassNotFound , because JAVA-CLASSPATH is set incorrectly.

+3
source

In your file, bat %~dp0 expands to the location of the bat file. You need this in your class path so Java can find the class, although I don't know if it will choke on the UNC path. For instance:

 @echo off echo %~dp0 

displays

 \\host\share\dir 

EDIT:% dp0 will not work if there are spaces. This is what you need in the bat file:

 @echo off set p=%~dps0 echo %p% java -classpath %p%\jarname classname pause 
+1
source

All Articles