Last active
February 26, 2020 07:03
-
-
Save pavel-mukhanov/12c37b3123267f29e05d75d394a26bba to your computer and use it in GitHub Desktop.
Parser refactoring
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.util.concurrent.locks.ReentrantLock; | |
/** | |
* This class allows to read/write content to provided file. | |
* Class is thread-safe. | |
*/ | |
public class ContentProvider { | |
private File file; | |
private ReentrantLock lock = new ReentrantLock(); | |
public ContentProvider(String fileName) { | |
this.file = new File(fileName); | |
} | |
public String getContent() throws IOException { | |
StringBuilder output = new StringBuilder(); | |
lock.lock(); | |
try (BufferedReader reader = new BufferedReader(new FileReader(file))) { | |
String line; | |
while ((line = reader.readLine()) != null) { | |
output.append(line); | |
output.append(System.lineSeparator()); | |
} | |
} finally { | |
lock.unlock(); | |
} | |
return output.toString(); | |
} | |
public String getContentWithoutUnicode() throws IOException { | |
StringBuilder output = new StringBuilder(); | |
lock.lock(); | |
try (FileInputStream input = new FileInputStream(file)) { | |
int symbol; | |
while ((symbol = input.read()) > 0) { | |
if (symbol < 0x80) { | |
output.append((char) symbol); | |
} | |
} | |
} finally { | |
lock.unlock(); | |
} | |
return output.toString(); | |
} | |
public void saveContent(String content) throws IOException { | |
lock.lock(); | |
try (BufferedWriter output = new BufferedWriter(new FileWriter(file))) { | |
output.write(content); | |
} finally { | |
lock.unlock(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment