I assume that the file you want to read is a true resource in your class path, and not just any arbitrary file that you can simply access through new File("path_to_file"); .
Try using ClassLoader , where resource is a String representation of the path to your resource file in your class path.
Valid String values ββfor resource may include:
"foo.txt""com/company/bar.txt""com\\company\\bar.txt""\\com\\company\\bar.txt"
and the path is not limited to com.company
Relevant code to get File not in JAR:
File file = null; try { URL url = null; ClassLoader classLoader = {YourClass}.class.getClassLoader(); if (classLoader != null) { url = classLoader.getResource(resource); } if (url == null) { url = ClassLoader.getSystemResource(resource); } if (url != null) { try { file = new File(url.toURI()); } catch (URISyntaxException e) { file = new File(url.getPath()); } } } catch (Exception ex) { }
Alternatively, if your resource is in a JAR, you will need to use Class.getResourceAsStream(resource); and scroll through the file using BufferedReader to simulate a call to readLines() .
source share