Home > database >  How to read txt file using Springboot?
How to read txt file using Springboot?

Time:07-14

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?

CodePudding user response:

Create a Spring Boot application and include the Spring Web facilities; Create a Spring @Controller class; Add a method to the controller class which takes Spring's MultipartFile as an argument; Save the uploaded file to a directory on the server; and.

CodePudding user response:

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));
  • Related