Can not find file that is in resource folder - java

I have a question regarding file handling. I automate a page using selenium, and I need to upload a file in this page. I want to put the file in resource folder and read it's path in the test (since many OS and path will be different to any computer WIN/MAC).

I put the file manually in the resource folder, and it put it in:

X:\Project_11_01_2021\src\test\resources

when I used the ClassLoader and try to find the file it not found it, I saw that if I manually put it in this path it find it, found.

X:\Project_11_01_2021\out\test\resources

the problem is that I am using git and if I add to the resources it upload to git and every one will get the change, and when I put in out\test\resources it is not displayed in the source tree to commit to git. is their a way that classLoader will search in the first location? and not in the second?

[enter image description here][path that worked]

[enter image description here][when here not worked]

/******* test *******/

public  void entertax() throws Exception {
    WebDriver deiver2 = getWebDriver();
  
    Thread.sleep(1000);
    ClassLoader classLoader = getClass().getClassLoader();
    String path = classLoader.getResource("TAX12.pdf").getPath();
    System.out.println("\n\n path is  " + path);
    deiver2.switchTo()
            .activeElement();
    deiver2.findElement(By.xpath("//input[@type='file']"))
    .sendKeys(
            "X:\\Project_11_01_2021\\out\\test\\resources\\fw8TAX12.pdf");



    System.out.println("END");

}

1 answer

  • answered 2021-01-16 13:48 Sebsen36

    This issue looks more like an IDE configuration problem.

    Your code classLoader.getResource("TAX12.pdf") looks correct (1. using classLoader.getResource() method && 2. specifying the correct relative path within the resources folder).

    I assume why the code fails to find the file is due to the fact that the resources folder is not part of your applications classpath (I'm assuming your trying to run the code from your IDE which apparently seems to be IntelliJ).

    I'm not regularly using IntelliJ, but you can specify the classpath settings in the Module settings.

    In the Module settings specify the resources folder as a resource:

    enter image description here

    When successfully added the resources folder to the classpath it should display an icon like this in the project explorer:

    enter image description here

    After adding the resources folder to your classpath everything should work.

    EDIT:

    In case you're using Maven also make sure to specify the resources folder as such in the pom.xml file correspondingly.

    Also make sure to spell the name of the file you're looking for "TAX12.pdf" correctly, since it seems to differ in your code and in your screenshots (not sure if it differs only because posting it here or also in your real code base).