Jeeppp
Jeeppp

Reputation: 1573

Spring boot resource file not found in server but works in Eclipse

I have a file in the resources directory of the spring boot app. I'm able to load it properly in eclipse. But when I build this project and run it on an server it throws java.nio.file.NoSuchFileException.

Whats wrong

I have the below class

class TestDataLoader{
@Value("${service.filename}")
private String filename;

@Inject
private FileLoader fileLoader;

public void loadResource(){
List<String> names = fileLoader.loadResource(filename);
}
}

This is my FileLoader class

public class FileLoader{
public List<String> loadResource(String filename) {
   try (Stream<String> stream = Files.lines(Paths.get(filename))) {
      // process the data
    } catch (IOException e) {
        LOGGER.error(e);
    }       
}
}

My application.yml file looks like below

service:
  filename: src/main/Myfile.txt

Upvotes: 0

Views: 1687

Answers (1)

JC Carrillo
JC Carrillo

Reputation: 1026

Tip 1: You should be placing resources in src/main/resources

When you run your server, your file is in the root. You should be okay by doing the chunk below:

service:
  filename: Myfile.txt

Tip 2: You should be using ClassPathResource. see below:

public class FileLoader{
  public List<String> loadResource(String filename) {
    Resource resource = new ClassPathResource(filename);
    File file = resource.getFile();
    Path path = file.toPath();
    try (Stream<String> stream = Files.lines(path)) {
      // process the data
    } catch (IOException e) {
      LOGGER.error(e);
    }       
  }
}

note: I haven't run the above code...

Upvotes: 1

Related Questions