Skip to content

Instantly share code, notes, and snippets.

@ruan65
Last active January 19, 2018 10:18
Show Gist options
  • Save ruan65/9896c41a547c63bc6dc85c6367adddef to your computer and use it in GitHub Desktop.
Save ruan65/9896c41a547c63bc6dc85c6367adddef to your computer and use it in GitHub Desktop.
java write to file exampe
@RequestMapping(value = "/change/text", method = RequestMethod.POST)
public OutputMessage changeText(@RequestBody InputMessage msg) {
String fileName = "/home/a/temp/writtenByJava.txt";
System.out.println("Writing to file " + fileName);
writeToFileHelper(fileName, msg.getText());
return new OutputMessage(msg.getFrom(), msg.getText() + " - this is response!", new Date().toString());
}
@RequestMapping("/read/text")
public String readWrittenText() {
String text = null;
try {
text = new String(Files.readAllBytes(Paths.get(fileName)));
} catch (IOException e) {
e.printStackTrace();
}
return text;
}
public static void writeToFileHelper(String fileName, String text) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(fileName))) {
bw.write(text);
System.out.println("Done!!!");
} catch (IOException e) {
e.printStackTrace();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment