I am trying to open a txt file which is located in my netbeans project folder but it says that the system cannot find the file specified.
File file = new File("Knowledge Base.txt");
I am trying to open a txt file which is located in my netbeans project folder but it says that the system cannot find the file specified.
File file = new File("Knowledge Base.txt");
When running on IDEs, the current directory is not always the directory where you place your .class
file.
Find out the current directory using
System.getProperty("user.dir")
And then make necessary changes to the path to get it to your directory.
The path given assumes an absolute path, so by not prefixing it it will assume it is in the root directory. To fix this, you can do this:
String path = new File(".").getAbsolutePath();
path=path.substring(0, path.length() - 1);
path+="Knowledge Base.txt"
File file = new File(path);
The first line gets the absolute path of the app file. The second subtracts the last character, leaving a / character for the directory. The third line adds your file to the string, and the fourth constructs a file object from the string. This method assumes that the file is located in the same folder as your class.
If your program is packaged as a .jar along with a libs folder, then you can do this instead.
String path = Test.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = URLDecoder.decode(path, "UTF-8");
decodedPath+="/Temp";
File file = new File(decodedPath);
This time we're getting the path to the .jar, then decoding it with UTF-8 because spaces would become "%20" if we didn't. You would need to replace "Test" with the name of your class, and "/Temp" with the path inside the .jar to the file. The rest is the same as the non .jar method, but we don't need to remove "." from the end of the string. Uses this Answer by Fab to decode the filepath for the .jar file.