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

The best Parser.java you ever seen #452

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
72 changes: 37 additions & 35 deletions Parser.java
Original file line number Diff line number Diff line change
@@ -1,46 +1,48 @@
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* This class is thread safe.
*/
import java.io.*;
import java.util.stream.IntStream;

public class Parser {
private File file;
public synchronized void setFile(File f) {
file = f;

public final File file;
private final FileInputStream inputStream;

public Parser(File file) throws IOException {
if (file == null) throw new IOException("input file is null");
this.file = file;
this.inputStream = new FileInputStream(file);
}
public synchronized File getFile() {
return file;

public void saveContent(String content) throws IOException {
var outputStream = new FileOutputStream(this.file);
for (int i : IntStream.range(0, content.length()).toArray()) {
outputStream.write(content.charAt(i));
}
outputStream.close();
}

public String getContent() throws IOException {
FileInputStream i = new FileInputStream(file);
String output = "";
int data;
while ((data = i.read()) > 0) {
output += (char) data;
}
return output;
return this.iterateOverContent(false);
}

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 this.iterateOverContent(true);
}

private String iterateOverContent(boolean unicode) throws IOException {
var builder = new StringBuilder();
int content;
while ((content = this.inputStream.read()) > 0) {
this.contentAsChar(unicode, builder, content);
}
return output;
this.inputStream.close();
return builder.toString();
}
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 void contentAsChar(boolean unicode, StringBuilder builder, int content) {
if (unicode && content > 0x80) {
return;
}
builder.append((char) content);
}

}