Skip to content

Instantly share code, notes, and snippets.

@pavel-mukhanov
Last active February 26, 2020 07:03
Show Gist options
  • Save pavel-mukhanov/12c37b3123267f29e05d75d394a26bba to your computer and use it in GitHub Desktop.
Save pavel-mukhanov/12c37b3123267f29e05d75d394a26bba to your computer and use it in GitHub Desktop.
Parser refactoring
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