10

I have the following code to read a text file.

public static void main(String[] args)
{
    try 
    {
    Scanner in = new Scanner(new FileReader("input.txt"));
    while(in.hasNext())
    {
        System.out.println(in.next());
    }
} 
catch (FileNotFoundException ex) 
{
    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}

I have my project structure set up as follows:

build/ directory contains class
dist/  directory contains the jar file 
src/ directory contains source
input.txt the text file to read

If I put my textfile input.txt into a directory called test which is of the same directory as build, dist, and src, what should go into the parameter of filereader so that I can still find this file?

Rhs
  • 3,188
  • 12
  • 46
  • 84

2 Answers2

10

When running inside the Netbeans IDE the working directory is the root of the project, so to answer your question, "test/input.txt".

Note however that while this is perfectly fine for testing code, working with relative paths like this in final (production) code can be trickier. In those cases wrapping the file as a resource in the jar and opening it as a resourcestream may be a better solution, or of course working with absolute paths.

fvu
  • 32,488
  • 6
  • 61
  • 79
  • Can you give me a bit more info on how to wrap the file as a resource in the jar? thanks – Rhs Jul 13 '13 at 14:39
  • On SO "daisychaining" questions is best avoided and this would lead us quite far off the original question. Have a look at some questions about that subject, eg [here](http://stackoverflow.com/questions/10605207/accessing-a-java-resource-as-a-file) or [here](http://stackoverflow.com/questions/13114852/using-resource-files-in-java) and many others (use the search functionality), and [this blog](http://capturevision.wordpress.com/2008/06/28/how-to-embed-resource-files-using-netbeans/) shows how to add them in NB. Should your run into problems do not hesitate to open a new question. – fvu Jul 13 '13 at 15:15
5

If you know the name of your subdirectory, just use

Scannner in = new Scanner(new FileReader("test/input.txt"));
eraelpeha
  • 409
  • 5
  • 15
  • 2
    the Windows version of Java is also capable of working with "test/input.txt" so the backslash version is not needed at all. – fvu Jul 13 '13 at 14:36