Skip to content

Commit 187d6ee

Browse files
committed
Ускорено чтение текстовых файлов
1 parent ff8c2d3 commit 187d6ee

File tree

2 files changed

+21
-18
lines changed

2 files changed

+21
-18
lines changed

src/com/annimon/ownlang/lib/modules/files.java

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -288,14 +288,18 @@ protected Value execute(FileInfo fileInfo, Value[] args) throws IOException {
288288
}
289289

290290
private static class readText extends FileFunction {
291+
292+
private static final int BUFFER_SIZE = 4096;
293+
291294
@Override
292295
protected Value execute(FileInfo fileInfo, Value[] args) throws IOException {
293-
final StringBuilder sb = new StringBuilder();
294-
int ch;
295-
while ((ch = fileInfo.reader.read()) != -1) {
296-
sb.append((char) ch);
296+
final StringBuilder result = new StringBuilder();
297+
final char[] buffer = new char[BUFFER_SIZE];
298+
int readed;
299+
while ((readed = fileInfo.reader.read(buffer, 0, BUFFER_SIZE)) != -1) {
300+
result.append(buffer, 0, readed);
297301
}
298-
return new StringValue(sb.toString());
302+
return new StringValue(result.toString());
299303
}
300304
}
301305

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,29 @@
11
package com.annimon.ownlang.parser;
22

3-
import java.io.BufferedReader;
3+
import java.io.ByteArrayOutputStream;
44
import java.io.FileInputStream;
55
import java.io.IOException;
66
import java.io.InputStream;
7-
import java.io.InputStreamReader;
87

98
public final class SourceLoader {
109

1110
public static String readSource(String name) throws IOException {
1211
InputStream is = SourceLoader.class.getResourceAsStream(name);
13-
if (is != null) return readStream(is);
12+
if (is != null) return readAndCloseStream(is);
1413

1514
is = new FileInputStream(name);
16-
return readStream(is);
15+
return readAndCloseStream(is);
1716
}
1817

19-
private static String readStream(InputStream is) throws IOException {
20-
final StringBuilder text = new StringBuilder();
21-
try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"))) {
22-
String line;
23-
while ((line = reader.readLine()) != null) {
24-
text.append(line);
25-
text.append(System.lineSeparator());
26-
}
18+
private static String readAndCloseStream(InputStream is) throws IOException {
19+
final ByteArrayOutputStream result = new ByteArrayOutputStream();
20+
final int bufferSize = 1024;
21+
final byte[] buffer = new byte[bufferSize];
22+
int readed;
23+
while ((readed = is.read(buffer)) != -1) {
24+
result.write(buffer, 0, readed);
2725
}
28-
return text.toString();
26+
is.close();
27+
return result.toString("UTF-8");
2928
}
3029
}

0 commit comments

Comments
 (0)