4

I am writing junit tests, where I need to read a file from src/test/resources

I have a following code in my src/test/java/some_packages/UserTests:

InputStream inputStream = new FileInputStream(new File("abc.txt"));

The file is of course present, but when I run my test I get java.io.FileNotFoundException: abc.txt (No such file or directory)

I marked resources folder as test resources in intellij

Bacteria
  • 8,406
  • 10
  • 50
  • 67
Pond
  • 41
  • 1
  • 1
  • 2
  • 1
    Your question does not make much sense. Do you want to read a file (based on it's filename) or to read a resource from the classpath? – jarnbjo Mar 18 '16 at 17:35
  • 1
    where is your abc.txt file stored? The problem is definitely the file is not found in the same directory as the compiled .class file. – Milind Gokhale Mar 18 '16 at 17:36
  • I want to read abc.txt file , which is located under resources folder – Pond Mar 18 '16 at 17:36

1 Answers1

12

new File("abc.txt") is relative to the working directory for your tests, not the src/test/resources directory. To access resources in the src/test/resources directory, get the resource from the class loader:

InputStream inputStream = getClass().getResourceAsStream("/abc.txt");
Darth Android
  • 3,437
  • 18
  • 19