DocumentFile implements Document, Closeable { @Override public void replace(final RegionByLine regionByLine, final String textToReplace) { try { tryToReplaceInFile(mapToRegionByOffset(regionByLine), textToReplace); } catch (final IOException e) { LOG.log(Level.WARNING, "An exception occurred when replacing in file " + filePath.toAbsolutePath()); } } 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 replaceATokenShouldSucceed() throws IOException { final String code = "int main(String[] args) {}"; writeContentToTemporaryFile(code); try (DocumentFile documentFile = new DocumentFile(temporaryFile, StandardCharsets.UTF_8)) { documentFile.replace(new RegionByLineImp(0, 0, 0, 3), "void"); } try (FileInputStream stream = new FileInputStream(temporaryFile)) { final String actualContent = new String(readAllBytes(stream)); assertEquals("void main(String[] args) {}", actualContent); } }
@Test public void replaceVariousTokensShouldSucceed() throws IOException { final String code = "int main(String[] args) {}"; writeContentToTemporaryFile(code); try (DocumentFile documentFile = new DocumentFile(temporaryFile, StandardCharsets.UTF_8)) { documentFile.replace(new RegionByLineImp(0, 0, 0, "int".length()), "void"); documentFile.replace(new RegionByLineImp(0, 0, 4, 4 + "main".length()), "foo"); documentFile.replace(new RegionByLineImp(0, 0, 9, 9 + "String".length()), "CharSequence"); } try (FileInputStream stream = new FileInputStream(temporaryFile)) { final String actualContent = new String(readAllBytes(stream)); assertEquals("void foo(CharSequence[] args) {}", actualContent); } }