Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NetBeans Java Project Path of Text File

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?

like image 738
Rhs Avatar asked Jul 13 '13 14:07

Rhs


2 Answers

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.

like image 160
fvu Avatar answered Sep 20 '22 18:09

fvu


If you know the name of your subdirectory, just use

Scannner in = new Scanner(new FileReader("test/input.txt"));
like image 25
eraelpeha Avatar answered Sep 18 '22 18:09

eraelpeha