Skip to content

Instantly share code, notes, and snippets.

@arnobroekhof
Created August 5, 2016 18:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arnobroekhof/84153bd5734fff4120410849274b7dd7 to your computer and use it in GitHub Desktop.
Save arnobroekhof/84153bd5734fff4120410849274b7dd7 to your computer and use it in GitHub Desktop.
public class ReadVeryBigFile {
public static void main(String[] args) throws Exception {
Runtime runtime = Runtime.getRuntime();
NumberFormat format = NumberFormat.getInstance();
long startedMemory = runtime.freeMemory();
String filename = "verybigfile.txt";
FileInputStream inputStream = null;
Scanner sc = null;
try {
inputStream = new FileInputStream(new File(filename));
sc = new Scanner(inputStream, "UTF-8");
while (sc.hasNextLine()) {
String line = sc.nextLine();
System.out.println(line);
}
// note that Scanner suppresses exceptions
if (sc.ioException() != null) {
throw sc.ioException();
}
}
finally {
if (inputStream != null) {
inputStream.close();
}
if (sc != null) {
sc.close();
}
}
System.out.println("free memory before: " + format.format(startedMemory / 1024) + "\n");
System.out.println("free memory after: " + format.format(runtime.freeMemory() / 1024) + "\n");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment