Created
August 5, 2016 18:58
-
-
Save arnobroekhof/84153bd5734fff4120410849274b7dd7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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