To save memory, do not unnecessarily store / duplicate data in memory (i.e. do not assign them to variables outside the loop). Just process the output as soon as input begins.
It doesn’t matter if you use BufferedReader or not. It will not cost much more memory, as some implicitly suggest. It will reach the highest level in only a few percent of productivity. The same applies to using NIO. This will improve scalability rather than memory usage. This will become interesting only when hundreds of themes will work in one file.
Just scroll through the file, immediately write each line to another file as you read it, count the lines and reach 100, then switch to the next file, etc.
Kickoff example:
String encoding = "UTF-8"; int maxlines = 100; BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream("/bigfile.txt"), encoding)); int count = 0; for (String line; (line = reader.readLine()) != null;) { if (count++ % maxlines == 0) { close(writer); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("/smallfile" + (count / maxlines) + ".txt"), encoding)); } writer.write(line); writer.newLine(); } } finally { close(writer); close(reader); }
BalusC Mar 01 '10 at 13:44 2010-03-01 13:44
source share