Skip to content

Instantly share code, notes, and snippets.

@shaiful16
Created October 6, 2016 03:26
Show Gist options
  • Save shaiful16/013007969635859b2cc3df8f3d05f04c to your computer and use it in GitHub Desktop.
Save shaiful16/013007969635859b2cc3df8f3d05f04c to your computer and use it in GitHub Desktop.
@CrossOrigin
@RequestMapping(value = "/fileRead", method = RequestMethod.GET)
public @ResponseBody String fileRead() throws Exception {
File file = new ClassPathResource("countries.txt").getFile();
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
System.out.println(file.getAbsolutePath());
System.out.println(file.getPath());
System.out.println("Total file size to read (in bytes) : " + fis.available());
int content;
while ((content = fis.read()) != -1) {
// convert to char and display it
System.out.print((char) content);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
return ex.getMessage();
}
}
return "done";
}
@CrossOrigin
@RequestMapping(value = "/fileWrite", method = RequestMethod.GET)
public @ResponseBody String fileWrite() throws Exception {
try {
String content = "This is the content to write into file";
File file = new ClassPathResource("countries.txt").getFile();
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
return "done";
} catch (IOException e) {
return e.getMessage();
}
}
}
@Aqil92
Copy link

Aqil92 commented Jan 14, 2019

helpfull

@olkunmustafa
Copy link

Writing part it is not working if the file is not created manually.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment