Ускорено чтение текстовых файлов

This commit is contained in:
Victor 2016-04-15 11:06:45 +03:00
parent ff8c2d39cd
commit 187d6eeae5
2 changed files with 21 additions and 18 deletions

View File

@ -288,14 +288,18 @@ public final class files implements Module {
} }
private static class readText extends FileFunction { private static class readText extends FileFunction {
private static final int BUFFER_SIZE = 4096;
@Override @Override
protected Value execute(FileInfo fileInfo, Value[] args) throws IOException { protected Value execute(FileInfo fileInfo, Value[] args) throws IOException {
final StringBuilder sb = new StringBuilder(); final StringBuilder result = new StringBuilder();
int ch; final char[] buffer = new char[BUFFER_SIZE];
while ((ch = fileInfo.reader.read()) != -1) { int readed;
sb.append((char) ch); while ((readed = fileInfo.reader.read(buffer, 0, BUFFER_SIZE)) != -1) {
result.append(buffer, 0, readed);
} }
return new StringValue(sb.toString()); return new StringValue(result.toString());
} }
} }

View File

@ -1,30 +1,29 @@
package com.annimon.ownlang.parser; package com.annimon.ownlang.parser;
import java.io.BufferedReader; import java.io.ByteArrayOutputStream;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader;
public final class SourceLoader { public final class SourceLoader {
public static String readSource(String name) throws IOException { public static String readSource(String name) throws IOException {
InputStream is = SourceLoader.class.getResourceAsStream(name); InputStream is = SourceLoader.class.getResourceAsStream(name);
if (is != null) return readStream(is); if (is != null) return readAndCloseStream(is);
is = new FileInputStream(name); is = new FileInputStream(name);
return readStream(is); return readAndCloseStream(is);
} }
private static String readStream(InputStream is) throws IOException { private static String readAndCloseStream(InputStream is) throws IOException {
final StringBuilder text = new StringBuilder(); final ByteArrayOutputStream result = new ByteArrayOutputStream();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"))) { final int bufferSize = 1024;
String line; final byte[] buffer = new byte[bufferSize];
while ((line = reader.readLine()) != null) { int readed;
text.append(line); while ((readed = is.read(buffer)) != -1) {
text.append(System.lineSeparator()); result.write(buffer, 0, readed);
}
} }
return text.toString(); is.close();
return result.toString("UTF-8");
} }
} }