Monday, December 12, 2011

getResouce and Files in java. I just hate having to search for this every time.

To get a file inside a jar, you have to do the following:

URI resourceURI = this.class.getResource("/path/to/file/in/jar/config.txt").toURI();

To open the file using a file you can do:

File theFile = new File(resourceURI);

To read the contents of the file:

List<String> lines = Files.readLines(theFile, Charsets.UTF_8);


To read the files in a directory:



// Load the directory as a resource
URL dir_url = ClassLoader.getSystemResource(dir_path);
// Turn the resource into a File object
File dir = new File(dir_url.toURI());
// List the directory
String files = dir.list()

No comments: