Home > Enterprise >  Why do I receive a NoSuchFileException error when loading a file?
Why do I receive a NoSuchFileException error when loading a file?

Time:12-29

Files.readString(Paths.get(ClassPathResource("temp.md").uri)

The markdown text in the src > main > resources folder is loaded through the code above. In the local environment, the file location is checked and data is loaded normally, but when the built jar is executed on ec2, the following error is returned.

I think, the path to the built jar is wrong, but I don't know how to solve it, please advise

CodePudding user response:

Alternatively we can read resource using classloader instance.

    ClassLoader classLoader = SpringBootResourcesApplication.class.getClassLoader();
    File file = new File(classLoader.getResource("temp.md").getFile());

CodePudding user response:

File loading from files located in the classpath work differently when the application is packed as a JAR.
Check this Baeldung article for the detailed explanation.
This will work independent from the way the code is packaged:

import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import org.springframework.util.ResourceUtils;

import java.nio.file.Files;

@UtilityClass
public class FileTestUtils {

    @SneakyThrows
    public byte[] getFileAsBytes(String fileName) {
        return Files.readAllBytes(ResourceUtils.getFile("classpath:"   fileName).toPath());
    }

    @SneakyThrows
    public String getFileAsString(String fileName) {
        return new String(Files.readAllBytes(ResourceUtils.getFile("classpath:"   fileName).toPath()));
    }

}
  • Related