Skip to content

Instantly share code, notes, and snippets.

@gaffo
Created November 11, 2018 17:42
Show Gist options
  • Save gaffo/18ee0ca83462ae389bcecd228765c0a5 to your computer and use it in GitHub Desktop.
Save gaffo/18ee0ca83462ae389bcecd228765c0a5 to your computer and use it in GitHub Desktop.
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
public class TextOutputExample {
public static void main(String args[]) throws FileNotFoundException {
PrintWriter out = new PrintWriter(new FileOutputStream("file.txt"));
out.println("hi there, graham");
out.println("how are you");
out.close(); // important
// Basically print writer prints to an in memory array
// and when you hae enough data for a write to disk (suually a multiple of
// 1024 bytes (characters), then
// print writer will actually push to disk
// calling close actually calls "flush", which does the above.
// close then closes the thing as well.
//
// if you were in the middle of a program and wanted to get data
// out to disk now (pretend it's a log file you're reloading)
// then you would call flush.
//
// this may be too much info... but
// java is a "garbage collected" language
// meaning that every few seconds the language looks for everything
// you aren't using anymore and fres up that memory for re-use
// it also does this at the end of main
//
// however, sometimes the program will exit before running everything
// from a garbage collector...
// and this can be bad becuase "close" is part of the
// garbage collection on Print Writer
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment