Code from target folder in java spring-boot

741 views Asked by At

I have generated a zip file in target folder using a maven-plugin, and now I aim to bring/take/read that zip file into a java class as logic need that zip for further process I tried with every possible way by providing paths to File f = new File(path); but everytime when I check with f.exists() or f.isFile() it gives false as most probably it is not able to find zip at that path, So I am not clear how and what path to give and no use cases are given in SO as well Can some one help.

tried with every suggested way Resource and resourceLoader cannot be used as its only used when we read something from src/main/resources, used File of java.io but failed everytime can someone explain what and how paths are given to read something from target folder in java spring boot

1

There are 1 answers

0
Nick Holt On

Interpreting your question a little, it sounds like you have a resource file that you want to access at runtime and that that resource file will not change after a build.

Resource files should be added to the src/main/resources; doing so will add the resource files into the root of the jar when it is built.

If you want the resource file to be in a directory within the jar, then just create that directory structure under the resources directory.

For example, if you want the resource file to be in some/directory, then you would put the resource file in src/main/resources/some/directory.

When you access the resource file, you do so from the classpath using either ClassLoader.getResource(String) or ClassLoader.getResourceAsStream(String).

For example, if I had a resource file called my-resources.txt, in src/main/resources/some/directory, the following would load and print this file from an Application.class:

public class Application
{
  private static final String RESOURCE_FILE = "some/directory/my-resources.txt";

  public static void main(String[] args) throws IOException
  {
    try (
      InputStream in = Application.class.getClassLoader().getResourceAsStream(RESOURCE_FILE);
      BufferedReader reader = in != null ? new BufferedReader(new InputStreamReader(in)) : null;
    )
    {
      if (in == null) throw new IllegalStateException("Failed to find: " + RESOURCE_FILE);

      String line;
      while ((line = reader.readLine()) != null) System.out.println(line);
    }
  }
}