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?
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.
If you know the name of your subdirectory, just use
Scannner in = new Scanner(new FileReader("test/input.txt"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With