Reputation: 3
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
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
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