Wednesday, March 4, 2020

How to load file(s) in the same directory

The code below demonstrates how to load file(s), eg configuration, properties in the same directory with the jar file or the running class file.


try {
    File jarLoc = new File(
                        MyClass.class.getProtectionDomain()
                        .getCodeSource().getLocation().toURI().getPath());

    if(!jarLoc.isDirectory()) {
        // if this is a jar file, the full path with jar name returned. 
        currentPath = jarLoc.getParentFile().getPath();
    } else {
        // if this is a class file, full path until the parent directory
        currentPath = jarLoc.getPath();
    }

    String pathToFile = "currentPath + fileName.fileExtension";

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


The code below demonstrates how to load file's content in the jar file or in the classpath.

        InputStream in = getClass().getResourceAsStream(path);
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line = null;
        String content = "";
        while ((line = reader.readLine()) != null) {
            content += line;
        }

OR

new String(Files.readAllBytes(Paths.get(path)))




Done!!

8 comments:

  1. Amazing performance out of small business web design and development web in addition to support!

    ReplyDelete
  2. They had a strong understanding of the project needs and delivered great work
    logo designing services

    ReplyDelete
  3. The team supplies valuable advice for improvements, demonstrates initiative in problem-solving, and always delivers in a timely and cost-effective manner.
    brand building firm

    ReplyDelete
  4. This short article posted only at the web site is truly good.
    San Francisco branding agencies

    ReplyDelete
  5. Waooow!!! Magnificent blogs, this is what I wanted to search. Thanks buddy
    top UX designer

    ReplyDelete
  6. I'm certainly very happy to read this blog site posts which carries plenty of helpful data, thanks for providing such information.
    top UX designers

    ReplyDelete
  7. This is such a great resource that you are providing and you give it away for free. I love seeing blog that understand the value of providing a quality resource for free. Sharepoint employee directory

    ReplyDelete
  8. Quality stuff may be the key to invite the users to visit begin to see the blog site, that’s what this site provides.
    companies in web development and UX/UI

    ReplyDelete

LinkWithin

Related Posts Plugin for WordPress, Blogger...