diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..67b3b98 --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +*.class + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* +*~ diff --git a/Parser.java b/Parser.java index d6d65d3..c42e397 100644 --- a/Parser.java +++ b/Parser.java @@ -2,26 +2,30 @@ import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; +import java.io.PrintWriter; +import java.nio.file.Files; + /** * This class is thread safe. */ public class Parser { private File file; + //I would remove the setter/getter for file and make it a parameter to the constructor. + //If a user needs to change the file, it should require a new parser. 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; - } - return output; + byte[] bytes = Files.readAllBytes(file.toPath()); + return new String(bytes); } + //TODO: implement a FilteredInputStream that takes a lambda for which characters to skip + //this would allow alternate cases to be easily implemented and use that stream to read + //the character. Also would use a stringbuffer instead of string concat (more performant) public String getContentWithoutUnicode() throws IOException { FileInputStream i = new FileInputStream(file); String output = ""; @@ -34,9 +38,7 @@ public String getContentWithoutUnicode() throws IOException { 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)); - } + PrintWriter writer = new PrintWriter(file); + writer.print(content); } }