Buffer reader and Buffer writer are the preferred classes to use when reading and writing too and from files.
You can achieve this a few ways.
Example 1 - Using File, FileWriter and BufferWriter classes with manual close :
File file = new File("Stock.txt");
FileWriter fr = new FileWriter(file, true);
BufferedWriter br = new BufferedWriter(fr);
br.write(data + "\n");
br.close();
fr.close();
Example 2 - Using File, FileWriter and BufferWriter classes with try-with-resource, which will auto-close the resource when processing has ceased :
File file = new File("Stock.txt");
try (FileWriter fileWriter = new FileWriter(file, true);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) {
bufferedWriter.write(data + "\n");
} catch (FileNotFoundException e) {
System.out.println("Unable to open file, file not found.");
} catch (IOException e) {
System.out.println("Unable to write to file." + file.getName());
}
See: https://stackabuse.com/reading-and-writing-files-in-java/ for some really useful info on reading and writing files!
See: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html for info on try-with-resource.