4

I want to read the contents of a file in the classpath (in resources/) to a String. Does Spring have a convenience annotation for that?

Something like:

public class MyClass {
    @Resource("classpath:data.txt")
    private String data;
}

Is something like that available in Spring?

2 Answers2

2
@Value("classpath:data.txt")
private Resource data;

You can't inject a String, but you can use a Spring abstraction called Resource to obtain a file and read its content on your own.

I think Spring places that responsibility on you because otherwise it would very fragile; different IO things may happen during accessing/reading a resource resulting in an IOException.

In addition, file-to-string conversions aren't that common to make Spring implement it.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
1

The @Value annotation is used to inject property values into variables, usually Strings or simple primitive values. You can find more info here.

If you want to load a resource file, use a ResourceLoader like:

@SpringBootApplication
public class ExampleApplication implements CommandLineRunner {

    @Autowired
    private ResourceLoader resourceLoader;

    @Autowired
    private CountWords countWords;

    public static void main(String[] args) {
        SpringApplication.run(ExampleApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println("Count words : " + countWords.getWordsCount(resourceLoader.getResource("classpath:file.txt")));

    }
}

Another solution, you can to use @Value like:

@SpringBootApplication
public class ExampleApplication implements CommandLineRunner {


    @Value("classpath:file.txt")
    private Resource res;

    @Autowired
    private CountWords countWords;

    public static void main(String[] args) {
        SpringApplication.run(ExampleApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println("Count words : " + countWords.getWordsCount(res));

    }
}
Jose Luque
  • 452
  • 6
  • 15