javaapirestfile

Java receiving text file inputs in REST


Let's say I have a GET endpoint which receives a String ("this is a string") and returns a modified version of it ("This is a string!"):

@GetMapping(value = "/test")
@ResponseBody
public String getText(@RequestParam String text) {
    return modified(text);
}

How would I adjust this code for it to receive the same piece of text in a .txt file?


Solution

  • @GetMapping(value = "/try")
    @ResponseBody
    public String getText(@RequestParam("filePath") String filePath) throws 
    IOException {
    File file = new File(filePath);
    BufferedReader reader = new BufferedReader(new FileReader(file));
    String line = reader.readLine();
    StringBuilder builder = new StringBuilder();
    while (line != null) {
        builder.append(line);
        line = reader.readLine();
    }
    reader.close();
    return modified(builder.toString());
    

    }