From 8041b843f62ad167a92d48bc502f94bc492f73de Mon Sep 17 00:00:00 2001 From: Audiz Date: Thu, 13 Jan 2022 15:55:06 +0500 Subject: [PATCH] Refactoring for Parser --- Parser.java | 93 +++++++++++++++++++++++++++++++++-------------------- 1 file changed, 58 insertions(+), 35 deletions(-) diff --git a/Parser.java b/Parser.java index c13a9fe..c8a912c 100644 --- a/Parser.java +++ b/Parser.java @@ -2,45 +2,68 @@ import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; + /** + * IO operations with file. * This class is thread safe. - */ + * TODO: Rename the 'Parser' name to 'SyncFileOperations' + * */ 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; + private final File file; + private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(true); + + public Parser(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; - } + + /** + * Read file content + */ + public String getContent() throws IOException { + readWriteLock.readLock().lock(); + try (FileInputStream inputStream = new FileInputStream(file)) { + StringBuilder output = new StringBuilder(); + int data; + while ((data = inputStream.read()) > 0) { + output.append((char) data); + } + inputStream.close(); + return output.toString(); + } finally { + readWriteLock.readLock().unlock(); + } } - return output; - } - 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(); + + /** + * Save content to file + * */ + public void saveContent(String content) { + readWriteLock.writeLock().lock(); + try { + try (FileOutputStream outputStream = new FileOutputStream(file)) { + outputStream.write(content.getBytes(StandardCharsets.UTF_8)); + } catch (IOException e) { + e.printStackTrace(); + } + } finally { + readWriteLock.writeLock().unlock(); + } + } + + /** + * TODO: Data should be cleaned outside the class. + **/ + @Deprecated + public String getContentWithoutUnicode() throws IOException { + StringBuilder output = new StringBuilder(); + for (char ch : getContent().toCharArray()) { + if (ch < 0x80) { + output.append(ch); + } + } + return output.toString(); } - } }