1

File not found exception in java even though file exists in src folder, src folder has 2 files kaif.xml and PropertiesDemo.java

FilePath: C:\Users\sam\Desktop\javatest\Java\BasicJava\PropertiesDemo_loadFromXML_App\PropertiesDemo\src\kaif.xml

PropertiesDemo.java

class PropertiesDemo
{

    public static void main(String[] args) throws IOException
    {
        Properties p = new Properties();

        try (FileInputStream fis = new FileInputStream("kaif.xml"))
        {
            
            p.loadFromXML(fis);

            Enumeration<?> enumeration = p.propertyNames();

            while (enumeration.hasMoreElements())
            {
                String key = (String) enumeration.nextElement();
                String value = p.getProperty(key);

                System.out.println(key + " = " + value);
            }

        }

    }
}
asif kaif
  • 159
  • 12
  • 1
    check this out https://stackoverflow.com/a/19309163/12709358 – Elango Mar 23 '22 at 03:17
  • Specifically use the complete relative path from your run directory (The location you started your jar from), for example `new FileInputStream("PropertiesDemo/src/kaif.xml")` or the full path `new FileInputStream("C:/Users/sam/Desktop/javatest/Java/BasicJava/PropertiesDemo_loadFromXML_App/PropertiesDemo/src/kaif.xml")` note when using a path use `/` or `\\ `, because `\ ` is an escape character in strings. – sorifiend Mar 23 '22 at 03:25
  • 3
    Do not, ever, under any circumstances, reference `src` in ANY path in your code. `src` will NOT exist once you export the app (in any meaningful way). Depending on your IDE/build system, a file in `src` should be treated as an "embedded" resource, this is one which will be reachable from the app via the apps classpath. To load the file, you should be using `PropertiesDemo.class.resourceAsStream("/kaif.xml"`) – MadProgrammer Mar 23 '22 at 04:13
  • If you do not want to embed `"kaif.xml"` in you app, then it should be stored (and referenced) with context to the "working directory", that is, relative to where the `java` command executed (not where the class file exists). For example, without change the code, you could move the file to `C:\Users\sam\Desktop\javatest\Java\BasicJava\PropertiesDemo_loadFromXML_App\PropertiesDemo` and execute `java` from that location – MadProgrammer Mar 23 '22 at 04:21

0 Answers0