1

I have an initialization file (initialize.java) that pulls in data from fileInput.txt using a fileInputStream, but both of them are in different directories.

Project/library/initialize.java
Project/resources/text/fileInput.txt

my code in initialize.java is:

FileInputStream fstream = new FileInputStream("/resources/text/fileInput.txt");

But the file cannot be read. I've also tried

FileInputStream fstream = new FileInputStream("./resources/text/fileInput.txt");

But that didn't work too.

How can I access the txt file and what's the difference between using "./resources" and "/resources"?

Thanks for reading this.

puissant
  • 781
  • 2
  • 10
  • 17
  • Thanks for all the help guys. I realized it was my big mistake but at least i learnt the "./" Directory stuff :) – puissant Mar 13 '12 at 07:45

4 Answers4

6

The difference is huge. On // the path starting with / starts from root directory. The path starting with ./ or without starting from current application directory. Call

System.out.println(new File("."). getAbsolutePath()) to check where you are?

Andrzej Jozwik
  • 14,331
  • 3
  • 59
  • 68
  • Silly me.. I did the absolute path thing and found out it was actually Project/src/library and i had to do a "new FileInputStream("src/resources/...") thank you!! – puissant Mar 13 '12 at 07:43
  • 1
    Maybe the problem is that resources is your root folder in resources. So try [InputStream in = ClassLoader.getResourceAsStream("/text/fileInput.txt")](http://docs.oracle.com/javase/6/docs/api/java/lang/ClassLoader.html#getResourceAsStream(java.lang.String)) or `InputStream in = ClassLoader.getResourceAsStream("text/fileInput.txt")`, I've never known :). Now the root is your classpath root. – Andrzej Jozwik Mar 13 '12 at 07:58
2

FileInputStream fstream = new FileInputStream("resources/text/fileInput.txt");

Tried this?

CoNgL3
  • 56
  • 4
2

"./resources/text/fileInput.txt" or "resources/text/fileInput.txt" works, but "/resources/text/fileInput.txt" doesn't.

Note: This is valid if the folder named "resources" is located under the root directory of your project.

Juvanis
  • 25,802
  • 5
  • 69
  • 87
1

As the other answers suggest, the path you pass to FileInputStream depends on the OS and also if the path is a relative or an absolute path. Another way of reading the file is to use Class.getResourceAsStream() instead. e.g.

InputStream is = this.getClass().getResourceAsStream("/resources/text/fileInput.txt")

For the above to work, you need to have the parent folder of /resources in the classpath. For more information on how getResourceAsStream works, see SO question

Community
  • 1
  • 1
Suresh Kumar
  • 11,241
  • 9
  • 44
  • 54