From f49484787b4f6da76f47cd0e4992888833ab9927 Mon Sep 17 00:00:00 2001 From: Srinivas Iyengar Date: Wed, 28 Sep 2016 23:37:35 +0530 Subject: [PATCH] Quick Refactoring of Parser.java --- Parser.java | 71 ++++++++++++++++++++++++++++++----------------------- 1 file changed, 40 insertions(+), 31 deletions(-) diff --git a/Parser.java b/Parser.java index d6d65d3..7840818 100644 --- a/Parser.java +++ b/Parser.java @@ -2,41 +2,50 @@ import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.function.Function; + /** * This class is thread safe. */ public class Parser { - private File file; - public synchronized void setFile(File f) { - file = f; - } - public synchronized File getFile() { - return file; - } - public String getContent() throws IOException { - FileInputStream i = new FileInputStream(file); - String output = ""; - int data; - while ((data = i.read()) > 0) { - output += (char) data; + public static final int ASCII_VALUE = 0x80; + private final File file; + + public Parser(final File file) { + this.file = file; } - return output; - } - 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; - } + + public File getFile() { + return file; } - return output; - } - public void saveContent(String content) throws IOException { - FileOutputStream o = new FileOutputStream(file); - for (int i = 0; i < content.length(); i += 1) { - o.write(content.charAt(i)); + + public String getContent() throws IOException { + return getContentWithFilter(c -> true); } - } -} + + public String getContentWithoutUnicode() throws IOException { + return getContentWithFilter(c -> c < ASCII_VALUE); + } + + private String getContentWithFilter(final Function filterFunction) throws IOException { + final StringBuilder stringBuilder = new StringBuilder(); + try (final InputStream inputStream = new FileInputStream(file)) { + int data; + while ((data = inputStream.read()) > 0) { + if (filterFunction.apply(data)) { + stringBuilder.append((char) data); + } + } + } + return stringBuilder.toString(); + } + + public synchronized void saveContent(final String content) throws IOException { + try (final OutputStream outputStream = new FileOutputStream(file)) { + outputStream.write(content.getBytes()); + } + } + +} \ No newline at end of file