2

This is a snapshot of a folder i imported into eclipse. I want to read from the .txt files inside it.

enter image description here

But if i write like

try(BufferedReader h = new BufferedReader(new FileReader("input8.txt"))){

i get FileNotFoundException . Can someone help out ?

Edit: Agad and Math's answers helped out a lot. I did a refined search again , found This article quite a good read for this particular problem once agad pointed things out.

Community
  • 1
  • 1
Somjit
  • 2,503
  • 5
  • 33
  • 60

2 Answers2

3
try(BufferedReader h = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("collinear/input8.txt")))){
agad
  • 2,192
  • 1
  • 20
  • 32
  • Why should this be needed ? seems a bit too much effort for something simple like this! I'll try it out none the less. – Somjit Sep 18 '13 at 14:27
  • I'm retarded , and i dont know how to chain this with a BufferedReader (if at all that should be done). Can you provide a little more code ? – Somjit Sep 18 '13 at 14:30
  • 1
    @SomjitNag execution directory can be anything. new FileReader(path) reads the file on path relative to execution directory, but you need path relative to class, you read the file from. – agad Sep 18 '13 at 14:30
1

Try:

"PatternRecognition\\collinear\\input8.txt"

EDIT

Answering OP's comment: This is the relative path starting from your project root, yours doesn't work because you didn't say the path of the file, you may have several files with the same name but in different paths, how would compile knows which one are you referring to if you don't say where is it? However, my answer is not as good as the agad answer IF you want to distribute your application from within a jar file, because as per his answer you may include all the needed resource within your jar file, meanwhile my solution would demand the files to go outside the jar. The better answer depends on what you need, and this is up to you decide.

Math
  • 3,334
  • 4
  • 36
  • 51
  • This works also , But i need to understand why it does , and why the one i tried didn't. Can you help me out a bit there ? – Somjit Sep 18 '13 at 14:48