Suggestions how to optimize the code are welcome.
package at.ande.primenumbers; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.LineNumberReader; public class primenumbers { public static void main(String[] args) throws IOException { int i = 3; boolean newMark = false; File output; if (!((output = new File("output.txt")).exists())) { output.createNewFile(); } LineNumberReader lineReader = new LineNumberReader(new FileReader(output)); int lineNumbers = 0; String sLast = null; while ((sLast = lineReader.readLine()) != null) { lineNumbers++; if (lineReader.getLineNumber() == 1) { lineReader.mark(65365); } i = Integer.parseInt(sLast); } FileWriter fw = new FileWriter("output.txt", true); if (lineNumbers == 0) { fw.write("3\n"); fw.flush(); lineReader.mark(65535); } while (true) { try { lineReader.reset(); } catch (Exception e) { lineReader = new LineNumberReader(new FileReader(output)); newMark = true; } i = i + 2; while (true) { String sPrime = lineReader.readLine(); if (newMark && lineReader.getLineNumber() == 1) { lineReader.mark(65365); newMark = false; } int prime = 0; if (sPrime != null) { prime = Integer.parseInt(sPrime); } if (sPrime == null || i < (prime * prime)) { fw.write(i + "\n"); fw.flush(); break; } if (i % prime == 0) { break; } } } } }
update2: catchblock for .insert()