How to resolve error from classloader.getResource() method?

403 Views Asked by At

I am in a strange situation :

  String filename ="file"+  System.currentTimeMillis()+file.getOriginalFilename();
  // suppose the file name is "file123256chart.docx"
  Path templatePath = Paths.get(DocTemplateProcessor.class.getClassLoader().getResource(filename).toURI());

This code is giving me null pointer exception because it is not able to file the resource.

but if I write :

Path templatePath = Paths.get(DocTemplateProcessor.class.getClassLoader().getResource("file123256chart.docx").toURI());

It is working fine. On printing the file name, it prints exactly the same. Anyone has any idea why this is happening ? Thanks in advance.

Update 1 : I got the problem, I was taking file input as multipart file.

public response getTextList(@RequestPart("file") MultipartFile file) {
 String filename ="f"+  System.currentTimeMillis()+file.getOriginalFilename();

 String filePath = "/home/ubuntu/templateEditor/learnspring/src/main/resources/" + filename;
 
 java.nio.file.Files.copy(file.getInputStream(), Paths.get(filePath));

  Path templatePath = Paths.get(DocTemplateProcessor.class.getClassLoader().getResource(filename).toURI());

So in the first code, templatePath variable was getting initialized before the file was getting copied to my server. Is there any way to run that line after the file got copied in my server ?

1

There are 1 best solutions below

0
On

You can use this example for take file souce like srting:

  public static InputStream getAsInputStream(final String name) {
        final var inputStream = Thread.currentThread()
                .getContextClassLoader()
                .getResourceAsStream(name);
        if (inputStream == null) {
            throw new IllegalArgumentException("Resource file not found: " + name);
        }
        return inputStream;
    }

        public static String readResourceFile(final String name) {
            final var inputStream = getAsInputStream(name);
            try {
                return IOUtils.toString(inputStream, StandardCharsets.UTF_8.name());
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }