forked from yegor256/quiz
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Parser.java
67 lines (61 loc) · 1.72 KB
/
Parser.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import java.io.*;
import java.util.regex.Pattern;
/**
* This class is thread safe.
*/
public class Parser {
private volatile File file;
private static final int DEFAULT_BUFFER_SIZE = 4096;
private static final Pattern REGEX_NON_ASCII = Pattern.compile("[^\\x00-\\x7F]");
public void setFile(File f) {
file = f;
}
public File getFile() {
return file;
}
/**
* @return unfiltered content of the file
* @throws IOException
*/
public String getContent() throws IOException {
FileInputStream input = null;
try {
input = new FileInputStream(file);
InputStreamReader reader = new InputStreamReader(input);
StringWriter writer = new StringWriter();
char[] buffer = new char[DEFAULT_BUFFER_SIZE];
while (reader.read(buffer) > 0) {
writer.write(buffer);
}
return writer.toString();
} finally {
if (input != null) {
input.close();
}
}
}
/**
* @return filtered content of the file - only ASCII symbols
* @throws IOException
*/
public String getContentWithoutUnicode() throws IOException {
return REGEX_NON_ASCII.matcher(getContent()).replaceAll("");
}
/**
* Saves data to the file
*
* @param content String data to save into file
* @throws IOException
*/
public void saveContent(String content) throws IOException {
FileOutputStream o = null;
try {
o = new FileOutputStream(file);
o.write(content.getBytes());
} finally {
if (o != null) {
o.close();
}
}
}
}