Load CSV file located in the classpath for H2 Database

Tags: , , ,

For tests purposes, I want to create and fill some tables using SQL scripts as well as CSV files.

So I created a SQL script like this one:

) as select * from CSVREAD('classpath:/foo.csv');

The foo.csv file exists, and is located in src/test/resources.

When this script is run on Eclipse (where src/test/resources is defined as a source directory and thus is included in the classpath), I get the following error:

Caused by: java.io.FileNotFoundException: resource /foo.csv
    at org.h2.store.fs.FileSystemDisk.openFileInputStream(FileSystemDisk.java:388)
    at org.h2.util.IOUtils.openFileInputStream(IOUtils.java:708)
    at org.h2.tools.Csv.initRead(Csv.java:317)
    at org.h2.tools.Csv.readResultSet(Csv.java:217)
    at org.h2.tools.Csv.read(Csv.java:193)
    ... 49 more

What did I do wrong? How to use correctly the classpath: protocol to load a CSV file?

If I put the complete path for the file (like ... CSVREAD('C:my-projectsrctestresourcesfoo.csv');), then it works. But that’s not why I want to do 🙂

Note that I use the latest version of H2 (1.3.153) as I wanted to use the classpath: protocol to load my file.


Even if the official docs give the CSVREAD('classpath:/org/acme/data/address.csv') example, Sean Patrick Floyd suggested to remove the leading slash, i.e. having:

) as select * from CSVREAD('classpath:foo.csv');

and this is working!

Source: stackoverflow