package rocks.zipcode; import java.io.*; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; /** * @author leon on 16/11/2018. */ public class Document implements DocumentInterface { private final FileWriter fileWriter; private final File file; public Document(String fileName) throws IOException { this(new File(fileName)); } public Document(File file) throws IOException { this.file = file; this.fileWriter = new FileWriter(file); } @Override public void write(String contentToBeWritten) throws IOException{ BufferedWriter writer = new BufferedWriter(new FileWriter(file)); writer.write(contentToBeWritten); writer.close(); } @Override public void write(Integer lineNumber, String valueToBeWritten) throws IOException { List lines = null; try { lines = Files.readAllLines(file.toPath()); lines.set(lineNumber,valueToBeWritten); Files.write(file.toPath(), lines); } catch (IOException e) { e.printStackTrace(); } } @Override public String read(Integer lineNumber) throws IOException { try(Stream lines = Files.lines(Paths.get("target/file.txt"))){ String line = lines.skip(lineNumber).findFirst().get(); return line; } } @Override public String read() { StringBuilder builder = new StringBuilder(); try (BufferedReader br = new BufferedReader(new FileReader(file))) { String sCurrentLine; while ((sCurrentLine = br.readLine()) != null) { builder.append(sCurrentLine).append("\n"); } } catch (IOException e) { e.printStackTrace(); } return builder.toString().trim(); } @Override public void replaceAll(String stringToReplace, String replacementString) { Path path = Paths.get("target/file.txt"); Charset charset = StandardCharsets.UTF_8; String content = null; try { content = new String(Files.readAllBytes(path), charset); } catch (IOException e) { e.printStackTrace(); } content = content.replaceAll(stringToReplace, replacementString); try { Files.write(path, content.getBytes(charset)); } catch (IOException e) { e.printStackTrace(); } } @Override public void overWrite(String content) { try { Writer fileWriter = new FileWriter("target/file.txt", false); write(content); } catch (IOException e) { e.printStackTrace(); } } public List toList() { return null; } @Override public File getFile() { return null; } @Override public String toString() { return null; } }