Skip to content

Instantly share code, notes, and snippets.

@ClausPolanka
Created December 15, 2020 09:42
Show Gist options
  • Save ClausPolanka/a33caefd109a4e0ed1c80b59c1759dd2 to your computer and use it in GitHub Desktop.
Save ClausPolanka/a33caefd109a4e0ed1c80b59c1759dd2 to your computer and use it in GitHub Desktop.
package test.wordcount.fakes;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import static java.lang.String.join;
import static java.lang.System.lineSeparator;
import static java.nio.file.Files.readAllLines;
import static java.nio.file.StandardOpenOption.APPEND;
import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING;
public class TestFileSystemStopwords {
private String backupOfOriginalStopwords;
private File file;
public TestFileSystemStopwords(String filePath) {
getStopWordsFileFrom(filePath);
backupOriginalStopwords();
writeTextToFile("", TRUNCATE_EXISTING);
}
private void getStopWordsFileFrom(String filePath) {
URL url = getClass().getClassLoader().getResource(filePath);
if (url == null) {
throw new RuntimeException(filePath + " not found");
}
file = new File(url.getFile());
}
private void backupOriginalStopwords() {
try {
backupOfOriginalStopwords = join(lineSeparator(), readAllLines(file.toPath()));
} catch (IOException e) {
reset();
}
}
private void writeTextToFile(String text, StandardOpenOption... options) {
try {
Files.write(file.toPath(), text.getBytes(), options);
} catch (IOException e) {
reset();
}
}
public void addStopword(String stopword) {
writeTextToFile(stopword, TRUNCATE_EXISTING);
}
public void reset() {
file.setReadable(true);
writeTextToFile(backupOfOriginalStopwords);
writeTextToFile(lineSeparator(), APPEND);
}
public void lockFile() {
file.setReadable(false);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment