Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Code refactoring. + Synchronized methods getContent(), getContentWith… #453

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 44 additions & 38 deletions Parser.java
Original file line number Diff line number Diff line change
@@ -1,46 +1,52 @@
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
* This class is thread safe.
*/
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;
}
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;
}
}
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();
}
}
private File file;

public Parser(File f) {
file = f;
}

public File getFile() {
return file;
}

public String getContent() throws IOException {
StringBuilder builder = new StringBuilder();
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
builder.append(br.readLine());
}
return builder.toString();
}

public String getContentWithoutUnicode() throws IOException {
StringBuilder builder = new StringBuilder();
try (BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file))) {
byte[] bytes = new byte[1024];
while (fis.read(bytes) > 0) {
for (int i = 0; i < bytes.length; i++) {
if (bytes[i] < 0x80) {
builder.append((char) bytes[i]);
}
}
}
}
return builder.toString();
}

public void saveContent(String content) throws IOException {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
bw.write(content);
}
}
}