Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations sizbut on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

reading from file in actual directory

Status
Not open for further replies.

amasny

Programmer
Oct 6, 2003
20
PL
Hello,
Im trying to read from file placed in directory where class is placed. I use this statement:
BufferedReader in = new BufferedReader(new FileReader("subport.ini"))
I've got File not found exception: java.io.FileNotFoundException: subport.ini (system cannot find file specified).
My question is:
How to specify file for read. I can't put direct path for FileReader constructor.
Greetings Arek
 
How about this:

Code:
File baseDirectory = new File("C:/somedirectory");
BufferedReader in = new BufferedReader(new FileReader(new File(baseDirectory, "subport.ini"));
 
Skin that cat :

Code:
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("C:/somedirectory/subport.ini")));
 
Issue is that i cannot specify full path. I would like to specify only "subport.ini" which is in the same directory as
class read it.
 
I'm confused ...

Say your .class file is in C:\java\classes. Your ini file is here too.

You set your CLASSPATH to be %CLASSPATH%;C:\java\classes.

If you run "java MyClass" from C:\java\classes then you can say fine :

Code:
BufferedReader in = new BufferedReader(new FileReader("subport.ini"))
.

But if you run "java MyClass" from C:\anotherdir then it will look for your ini file in C:\anotherdir - not C:\java\classes.

So it depends on where you are running your class from - not whjere your class file is ...
 
You can determine your class location at runtime. In the class which read your subport.ini:

Code:
String path = 
this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
BufferedReader in = new BufferedReader(new FileReader(path+"subport.ini"));

This way you can run your class in any directory and still can locate subport.ini.
 
Thanks a lot to all of you.
Mainly to "byam": it was what i needed :)
 
Hi Byam ,
The code which u have given to find the location of classpath is simple awesome...
Its a good code..

vishnu
;-)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top