Вот пример того, как вы могли это сделать. Я включил заметки в код.
// We return a collection to:
// 1: Have a variable-length 'array' returned.
// 2: Abstract the internal implementation of the actual collection used.
// We take an InputStream, so our function is more dynamic in what way it can parse lines (i.e. not just from files)
// Note: this won't really work on a stream that does not end.
// We renamed the function, to be more representable to what it does
public Collection<String> readAllLines(InputStream stream)
throws IOException // We do not handle this ourselves, since that would take away some abstraction. But it is up to you.
{
// We're not doing try-with-resources now, because the caller owns the stream.
// We're also passing a charset, so that we support all languages.
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8));
// BufferedReader has a built-in stream for all its lines.
Stream<String> linesStream = reader.lines();
// We collect all our lines using a built-in collector that returns it as a list.
List<String> lines = linesStream.collect(Collectors.toList());
return lines;
}
А потом назвать это:
Collection<String> lines;
try(InputStream stream = getAssets().open(filename))
{
lines = readAllLines(stream);
}
Как я указывал в своем комментарии: при вашем подходе вы пытались прочитать, пройдя конец файла, как вы уже итерировали по нему один раз, чтобы сосчитать все строки. Коллекция - хороший способ решить эту проблему.
PS: Если вам нужна коллекция на основе индекса, вы можете изменить определение readAllLines
, чтобы вместо него возвращалось List
.