DocumentFile implements Document, Closeable { @Override public void insert(int beginLine, int beginColumn, final String textToInsert) { try { tryToInsertIntoFile(beginLine, beginColumn, textToInsert); } catch (final IOException e) { LOG.log(Level.WARNING, "An exception occurred when inserting into file " + filePath); } } DocumentFile(final File file, final Charset charset); @Override void insert(int beginLine, int beginColumn, final String textToInsert); @Override void replace(final RegionByLine regionByLine, final String textToReplace); @Override void delete(final RegionByLine regionByOffset); @Override void close();  }
@Test public void insertAtStartOfTheFileShouldSucceed() throws IOException { writeContentToTemporaryFile("static void main(String[] args) {}"); try (DocumentFile documentFile = new DocumentFile(temporaryFile, StandardCharsets.UTF_8)) { documentFile.insert(0, 0, "public "); } try (FileInputStream stream = new FileInputStream(temporaryFile)) { final String actualContent = new String(readAllBytes(stream)); assertEquals("public static void main(String[] args) {}", actualContent); } }
@Test public void shouldPreserveNewlines() throws IOException { final String testFileContent = IOUtils.toString( DocumentFileTest.class.getResource("ShouldPreserveNewlines.java"), StandardCharsets.UTF_8); writeContentToTemporaryFile(testFileContent); try (DocumentFile documentFile = new DocumentFile(temporaryFile, StandardCharsets.UTF_8)) { documentFile.insert(0, 0, "public "); } try (FileInputStream stream = new FileInputStream(temporaryFile)) { final String actualContent = new String(readAllBytes(stream)); assertEquals("public " + testFileContent, actualContent); } }
@Test public void insertVariousTokensIntoTheFileShouldSucceed() throws IOException { writeContentToTemporaryFile("static void main(String[] args) {}"); try (DocumentFile documentFile = new DocumentFile(temporaryFile, StandardCharsets.UTF_8)) { documentFile.insert(0, 0, "public "); documentFile.insert(0, 17, "final "); } try (FileInputStream stream = new FileInputStream(temporaryFile)) { final String actualContent = new String(readAllBytes(stream)); assertEquals("public static void main(final String[] args) {}", actualContent); } }
@Test public void insertAtTheEndOfTheFileShouldSucceed() throws IOException { final String code = "public static void main(String[] args)"; writeContentToTemporaryFile(code); try (DocumentFile documentFile = new DocumentFile(temporaryFile, StandardCharsets.UTF_8)) { documentFile.insert(0, code.length(), "{}"); } try (FileInputStream stream = new FileInputStream(temporaryFile)) { final String actualContent = new String(readAllBytes(stream)); assertEquals("public static void main(String[] args){}", actualContent); } }