diff --git a/Parser.java b/Parser.java index c13a9fe..425766e 100644 --- a/Parser.java +++ b/Parser.java @@ -1,46 +1,48 @@ -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -/** - * This class is thread safe. - */ +import java.io.*; +import java.util.stream.IntStream; + public class Parser { - private File file; - public synchronized void setFile(File f) { - file = f; + + public final File file; + private final FileInputStream inputStream; + + public Parser(File file) throws IOException { + if (file == null) throw new IOException("input file is null"); + this.file = file; + this.inputStream = new FileInputStream(file); } - public synchronized File getFile() { - return file; + + public void saveContent(String content) throws IOException { + var outputStream = new FileOutputStream(this.file); + for (int i : IntStream.range(0, content.length()).toArray()) { + outputStream.write(content.charAt(i)); + } + outputStream.close(); } + public String getContent() throws IOException { - FileInputStream i = new FileInputStream(file); - String output = ""; - int data; - while ((data = i.read()) > 0) { - output += (char) data; - } - return output; + return this.iterateOverContent(false); } + public String getContentWithoutUnicode() throws IOException { - FileInputStream i = new FileInputStream(file); - String output = ""; - int data; - while ((data = i.read()) > 0) { - if (data < 0x80) { - output += (char) data; - } + return this.iterateOverContent(true); + } + + private String iterateOverContent(boolean unicode) throws IOException { + var builder = new StringBuilder(); + int content; + while ((content = this.inputStream.read()) > 0) { + this.contentAsChar(unicode, builder, content); } - return output; + this.inputStream.close(); + return builder.toString(); } - public void saveContent(String content) { - FileOutputStream o = new FileOutputStream(file); - try { - for (int i = 0; i < content.length(); i += 1) { - o.write(content.charAt(i)); - } - } catch (IOException e) { - e.printStackTrace(); + + private void contentAsChar(boolean unicode, StringBuilder builder, int content) { + if (unicode && content > 0x80) { + return; } + builder.append((char) content); } + }