Jeena
Jeena

Reputation: 309

reading a file using File separator in java

I am trying to read content of a file in java but I need to make it platform independent. So, I did

FileInputStream fis = new FileInputStream(new File(File.separator + "com" + File.separator + "test.txt"));
BufferedReader  br = new BufferedReader(new InputStreamReader(fis));

I am trying to run it in eclipse. But I am getting FileNotFoundExcption. Right now my test.txt is in same location as my source file. Please can anyone guide me through it. Where exactly is eclipse trying to look for this file? Thanks in advance..

Upvotes: 2

Views: 2951

Answers (2)

Magic Octopus Urn
Magic Octopus Urn

Reputation: 178

File a = new File(File.separator + "com" + File.separator + "test.txt");
System.out.println(a.getAbsolutePath());

Will likely output something that you were not expecting.

If you post what that returns, I can tell you what your problem was/is.

It likely uses the project directory, which you can output using:

how to Locate the path of the Current project in Java, Eclipse?


Solution:

If the path on windows is:

C:\com\test.txt

But on linux you want:

/com/test.txt

You want to use:

new File(System.getenv("SystemDrive") + File.separator + "com" + File.separator + "test.txt")

As this will function as described above.

Upvotes: 3

Aubin
Aubin

Reputation: 14853

Absolute version, probably not what you want:

BufferedReader br = new BufferedReader( new FileReader( "/com/test.txt" ));

Relative version:

BufferedReader br = new BufferedReader( new FileReader( "com/test.txt" ));

The Java File object, specialized by OS, translate this generic path in a platform dependent form.

The path is relative to the execution path, Eclipse has a small role: you may give the root path of execution in the Run/Debug dialog.

Upvotes: 2

Related Questions