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

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 final int BUFFER_SIZE = 4096;
@Override
protected Value execute(FileInfo fileInfo, Value[] args) throws IOException {
final StringBuilder sb = new StringBuilder();
int ch;
while ((ch = fileInfo.reader.read()) != -1) {
sb.append((char) ch);
final StringBuilder result = new StringBuilder();
final char[] buffer = new char[BUFFER_SIZE];
int readed;
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;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public final class SourceLoader {
public static String readSource(String name) throws IOException {
InputStream is = SourceLoader.class.getResourceAsStream(name);
if (is != null) return readStream(is);
if (is != null) return readAndCloseStream(is);
is = new FileInputStream(name);
return readStream(is);
return readAndCloseStream(is);
}
private static String readStream(InputStream is) throws IOException {
final StringBuilder text = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"))) {
String line;
while ((line = reader.readLine()) != null) {
text.append(line);
text.append(System.lineSeparator());
}
}
return text.toString();
private static String readAndCloseStream(InputStream is) throws IOException {
final ByteArrayOutputStream result = new ByteArrayOutputStream();
final int bufferSize = 1024;
final byte[] buffer = new byte[bufferSize];
int readed;
while ((readed = is.read(buffer)) != -1) {
result.write(buffer, 0, readed);
}
is.close();
return result.toString("UTF-8");
}
}