File Not Found Exception

I’ve been trying to get my options menu working for the past few hours now and it’s just about finished; my only problem now is that the program, for some ridiculous reason, thinks that a file, that exists, doesn’t exist.

Here is where I’m loading the file:

public String[] loadFile(String filePath)
    {
        int lineCounter = 0;
        ArrayList<String> lines = new ArrayList<>();
        
        try
        {
            final URL url = new URL(getClass().getProtectionDomain().getCodeSource().getLocation().toString()+filePath);
            System.out.println(url);
            final BufferedReader bufferedReader = new BufferedReader(new FileReader(url.toString()));
            
            String line = null;
            
            while((line = bufferedReader.readLine()) != null)
            {
                lines.add(line);
                
                lineCounter++;
            }

            bufferedReader.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        
        return lines.toArray(new String[lines.size()]);
    }

Here is the error message:

java.io.FileNotFoundException: file:\C:\Users\Tyler\Java%20Projects\Text%20Based%20Game\build\classes\Options.txt (The filename, directory name, or volume label syntax is incorrect)
	at java.io.FileInputStream.open(Native Method)
	at java.io.FileInputStream.<init>(FileInputStream.java:138)
	at java.io.FileInputStream.<init>(FileInputStream.java:97)
	at java.io.FileReader.<init>(FileReader.java:58)
	at Core.ResourceHandler.loadFile(ResourceHandler.java:69)
	at Screens.ScreenMainMenu.<init>(ScreenMainMenu.java:25)
	at Core.GameCanvas.<init>(GameCanvas.java:37)
	at Core.GameFrame.<init>(GameFrame.java:21)
	at Core.GameFrame.main(GameFrame.java:46)

I’ve triple checked to make sure that the file does exist and that it has all of the needed information within, the information is a single integer on line 1 that say which music track to use. I’ve also tried a few different ways to point the program to the file but they all have the same result.

The way that I’m attempting to get it to work is that, no matter where the .jar file is, there will always be an Options.txt in the same folder that will contain all of the options for the program; this will be read from when the program starts up and then written to if anything is changed in the menu. Everything looks like it should work but the program is just keeps throwing a file not found exception…

Try using an absolute path (i.e. “C:\Users\Username\blah\blahblah\options.txt”). If that doesn’t work, then there’s something wrong with

getClass().getProtectionDomain().getCodeSource().getLocation().toString()+filePath

.
If that works, uh, could it be that you’re not refreshing the project? I doubt it, seem to remember you using netbeans (auto refresh ftw).
What is your argument for the loadFile method (String filePath, what are you setting filePath as)?

What does [icode]System.out.println(url);[/icode] give you?

Sorry for the late reply, I went to sleep right after making this thread.

@Jimmt
filePath is being set as “Options.txt”.

@HeroesGraveDev
Printing out the url gives me “file:/C:/Users/Tyler/Java%20Projects/Text%20Based%20Game/build/classes/Options.txt”, without the quotation marks.
This error is really weird because it’s pointing to the proper file yet it doesn’t think the file is there even though it is…

If the file is on your class-path (which it seems to be) then an alternative could be this:

... new BufferedReader( new InputStreamReader( YourClass.class.getResourceAsStream( "/Options.txt" ) ) );

Try this.


final URL url = getClass().getClassLoader().getResource(filePath);

This works if the file is in the classpath. Or else, the file isn’t in the classpath.

I don’t know the answer to this, try SHC or someone else’s answer, but it’s pointing to the path you fed it, not the actual existing file.

@SHC
Your suggestion doesn’t work. When printing out the url it comes out as null and then there is a null pointer exception because of that.

@StrideColossus
Your suggestion also gives a null pointer exception just as SHC’s did.

I’m not sure what a classpath is but the Options.txt file is supposed to be located outside of the .jar file, when I’ve finished the program and turned it into a .jar, so that it can be read from and written to.

look at accepted answer of:

Just tried doing it that way as well but I’m still getting a NullPonterException.

public String[] loadFile(String filePath)
    {
        int lineCounter = 0;
        ArrayList<String> lines = new ArrayList<>();
        
        try
        {
            URL url = ClassLoader.getSystemResource(filePath);
            final BufferedReader bufferedReader = new BufferedReader(new FileReader(url.toString()));
            
            String line = null;
            
            while((line = bufferedReader.readLine()) != null)
            {
                lines.add(line);
                
                lineCounter++;
            }

            bufferedReader.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        
        return lines.toArray(new String[lines.size()]);
    }

java.io.FileReader doesn’t take URLs, or string representations of URLs, as parameters to its constructor; it expects a (local) file path. When you pass a string with “%20” embedded in it to represent a space, the class will assume you mean literally “%20”, and not a space character. Hence the file isn’t found, because what you passed to it literally does not exist.

You need to pass the file name “normally,” not URL-encoded. Or use some other construct, such as


new BufferedReader(new InputStreamReader(classLoader.getResourceAsStream("/path/to/resource")));

Are you just trying to read in a .txt file? Wouldn’t it be easier to just use Scanner.

Another problem could be that your file isn’t being placed in the right spot. In Eclipse or Netbeans, I think that files within the “build” folder are completely ignored and can’t be read by the program. If I were you, I’d try putting it in a folder called “data” or something completely different.

Actually, the latter solution might be better to try than the former.

Are you sure you have the correct permission for that file? Have you tried reading it as a stream (seems you have) and not as a file? If it is in your classpath (try putting it in the same folder as the class the reader is being called from. If the structure is like so:


-SomePackageInClassPath
  -SomeReaderClass.java
 OR
  -SomeOtherPackageOrFolder
    -SomeOtherPackageOrFolder
      ..etc
       -SomeReaderClass.java
-SomeFolder_or_SomePackage1
  -SomeFolder_or_SomePackage2
    -SomeFile.txt

Then the following in

SomeReaderClass.java

will work inside .jar or in eclipse.


public BufferedReader readFileAsBuffer(String fileName) {
		BufferedReader reader = null;
		reader = new BufferedReader(new InputStreamReader(getClass()
				.getResourceAsStream(fileName)));
		return reader;
	}


readFileAsBuffer("/SomeFolderOrPackage1/SomeFile.txt");

If the file is inside SomeFolderOrPackage1 and not under SomeFolderOrPackage2 then the following


readFileAsBuffer("/SomeFile.txt");

Should work.

Yeah, that’s all I’m trying to do — Looks like I’ve completely over complicated this…

Edit: Just implemented a scanner and now my file loader is working perfectly.

Thanks for the help everyone, I can’t believe how easy this was to solve; at least I won’t need to do this again now that I know how to do it!