Robin kumar
Robin kumar

Reputation: 3

how can we read a file using rest Api, which is locally present in my system?

I have to make a controller class and there I have to define get method to read a txt file which i have in my local storage.I made a controller and I don't know if it is really a correct one

Upvotes: 0

Views: 3037

Answers (2)

Ashish Patil
Ashish Patil

Reputation: 4604

It looks like your text file has new lines. So can you try using streams?

@RestController
@RequestMapping("/api")
public class Controller {

    @GetMapping("/file")
    String getData(){
       String strLine="";
        try (BufferedReader br = new BufferedReader(new FileReader(new File("/path"))))
        {
            strLine= br.lines().collect(Collectors.joining("\n"));  //this way next line text can also be returned into existing string & strLine will looks like exactly as your text file content
        } catch (IOException e) {
            e.printStackTrace();
        }
      return strLine;
    }

}

Upvotes: 0

Lunatic
Lunatic

Reputation: 1906

There are many ways to do so, one practice as follow

@RestController
@RequestMapping("/api")
public class Controller {

    @GetMapping("/file")
    ResponseEntity<?> inquiryAdAccess(){
        try (BufferedReader br = new BufferedReader(new FileReader(new File("/path"))))
        {
            return ResponseEntity.status(HttpStatus.OK).body( br.readAllLines());
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

}

Upvotes: 1

Related Questions