javaspring-bootspring-mvctxtfile-read

How to read txt file using Springboot?


I need to read a txt file using Springboot. This txt file consist of several words and need to assign those words in to a String Array. How can I do that?


Solution

  • Since your question is too vague, it becomes nearly impossible to know what you are expecting. I'll assume that you want to read a file from the classpath. If you were expecting something else, please clarify it clearly.

    You can use ClassPathResource to get the file name. And then you can handle files with FileReader or BufferedReader as you would normally handle files with Java.io. In a Spring Boot Application src/main/resources is the default classpath. So the String argument in the ClassPathResource constructor call must be relative to the classpath.

    Resource resource = new ClassPathResource("test.txt");
    File file = resource.getFile();
    BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
    
    String[] array = bufferedReader.lines().collect(Collectors.joining()).split(",");
    System.out.println(Arrays.asList(array));