简体   繁体   中英

How do I gain access to the files within the resources directory in my Maven web service project?

My Maven web service project has this basic structure:

MyWebService\
|-- src\
|   |-- main\
|   |   |-- java\
|   |   `-- resources\
|   |       `-- csvfiles\
|   |           `-- data.csv
|   `-- test\
`-- target\
    |-- classes\
    `-- test-classes\

I am trying to access the .csv files in the csvfiles subdirectory of my resources subdirectory.

I have a class with this code:

public class ReadCSVFiles {
    public void read(){
        String separator = System.getProperty("file.separator");
        ClassLoader cl = ReadCSVFiles.class.getClassLoader();
        URL url = cl.getResource(separator + "src" + separator + "main" + separator + "resources" + separator + "csvfiles" + "data.csv");
        url.toString();
    }
}

The path ends up being:

\src\main\resources\csvfiles\data.csv

I also tried this path:

src\main\resources\csvfiles\data.csv

Whenever I run my application, I always get a NullPointerException on the url.toString() line.

So, how do I go about getting access to those .csv data files?

If you're using the classloader to get a resource in the classpath (resources folder), just use the relative path:

ReadCSVFiles.class.getClassLoader().getResource("csvfiles/data.csv");

Javadoc

First of all I'm not sure why do you want to print the URL here, the classLoader.getResource has taken your resource directory as the root here. If you want to read the CSV and do some action on that that file then directly read the file using an InputStream.

Like the below

public class ReadCSVFiles {
public void read(){
    String separator = System.getProperty("file.separator");
    ClassLoader cl = ReadCSVFiles.class.getClassLoader();
     try (InputStream inputStream = cl.getResourceAsStream("csvfiles/data.csv")) {

        InputStreamReader streamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
        BufferedReader reader = new BufferedReader(streamReader);
       for (String line; (line = reader.readLine()) != null;) {
          // Process line
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

Or if you need to get the URL and then load the file through the URL you can try something like below

URL url = cl.getResource("csvfiles/data.csv");
Path path = Paths.get(url.toURI());
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM