3

I am writing a small test to read a CSV file (using testng). I found some code to do just that and some other lines to find the resource folder itself.

Now as I am re-using this in other scenarios, I thought that I could just create a util method instead of copy pasting:

public static String prepFilepath(Class c) {

    URL url = c.getResource("");
    String location = url.getPath();

    String packageName = c.getPackage().getName().replace(".", "/");

    int l = location.lastIndexOf(packageName);
    return location.substring(0, l);
}

and it is called by my test like this:

@Test
public void testImport(){
    File testFile = new File(ImportUtils.prepFilepath(this.getClass()), inputFileName);
    //...
}

However I don't know if it is the correct way:

  • Is it ok to pass a class reference as parameter? (I had never done that before for such a small purpose)
  • Are there more elegant ways?
  • Is it generic enough to justify the util?

Edit: I am using testng

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
olliaroa
  • 71
  • 7
  • Note that you can let JUnit give you the name of the test: http://stackoverflow.com/questions/473401/get-name-of-currently-executing-test-in-junit-4 – aioobe Dec 10 '14 at 14:45
  • 3
    Why don't you load the CSV stream from the classpath using Class.getResourceAsStream()? – JB Nizet Dec 10 '14 at 14:52
  • 1
    Here is an old Javaworld article which describes how to load a properties file as a classpath resource; it applies to all types of files though: http://www.javaworld.com/article/2077352/java-se/smartly-load-your-properties.html – Gimby Dec 10 '14 at 15:19

1 Answers1

0

If the file is in the same package as the class then we can get URL to the file this way

URL url = getClass().getResource(fileName);

if we need to get File from URL we can do it this way

File file = new File(url.toURI());
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275