Relative File IO
One problem with file IO inside of Java is that it depends on absolute file paths to be specified. This can cause a problem when trying to read files while inside a J2EE container for instance. However, there is a better way of reading files that allows you to move files without breaking any code. Try the following:
try {
InputStream in =
this.getClass().getResourceAsStream("testFile.txt");
BufferedReader bReader =
new BufferedReader(new InputStreamReader(in));
String line = bReader.readLine();
while (line != null) {
System.out.println(line);
line = bReader.readLine();
}
}
catch (Exception e) {
e.printStackTrace();
}
By using the getResourceAsStream method, it will search for the given file within the classpath of your application. This allows you to drop the files anywhere within that classpath and the file will still be read.
In order to test this, I set the above code up as a project in NetBeans, created the testFile.txt file and ran the program. The above code finds the file and simply prints it out to the screen. I then moved the file within the package structure and it continued to work.