0

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");
  • don't use spaces in file names! – Sergej Dec 02 '17 at 15:41
  • @Sergej Why? It's perfectly fine to use spaces in file names. – BackSlash Dec 02 '17 at 15:42
  • I just runned File file = new File("."); for(String fileNames : file.list()) System.out.println(fileNames); and my file appear there. – user8928579 Dec 02 '17 at 15:43
  • 1
    check if your file is in the correct directory = System.out.println(System.getProperty("user.dir")); , else place the file in the directory – Roshan Dec 02 '17 at 15:46
  • @BackSlash read more here: https://superuser.com/questions/29111/what-technical-reasons-exist-for-not-using-space-characters-in-file-names – Sergej Dec 02 '17 at 15:48

2 Answers2

1

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.

Sayan Sil
  • 5,799
  • 3
  • 17
  • 32
  • Great! Then please take some time to write a separate answer on how you fixed it or select one as accepted. – Sayan Sil Dec 02 '17 at 15:52
0

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.