InputStream / Reader无法正确读取资产文件

时间:2019-01-14 12:12:00

标签: java android android-studio

我想构建自己的密码生成器。因此,我创建了包含所有符号的文件,这些文件当前位于手动创建的文件夹“资产”中。我还创建了一个方法,该方法将以字符串数组形式返回单个文件的内容。该方法似乎已经可以识别给定的文件,因为它没有捕获"FileNotFoundException",并且可以正确获取文件的行数。现在我的问题是,返回的数组不包含文件的内容,而只是"null"s的数量,与文件的行数相对应。 我希望信息能做到。 谁能帮我吗?

我已经尝试使用其他字符集并将文件移动到文件夹"/res/raw/"

public String[] getList(String filename) {

    String[] zeichenliste = new String[0];

    try {
        InputStream is = getAssets().open(filename);
        BufferedReader br = new BufferedReader (new InputStreamReader(is));
        int length = 0;

        while (br.readLine() != null) length++;
        zeichenliste = new String[length];

        br = new BufferedReader (new InputStreamReader(is));
        for (int i = 0; i < length; i++) zeichenliste[i] = br.readLine();
        br.close();
        is.close();

    } catch (IOException e) {
        e.printStackTrace();
        return(null);
    }
    return zeichenliste;
}

2 个答案:

答案 0 :(得分:0)

这是您如何做的一个例子。我已在代码中包含注释。

// 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);
}

正如我在评论中指出的那样:在您的方法中,您尝试读取传递了文件的末尾,因为您已经对其进行了一次遍历以计数所有行。 Collection是解决此问题的好方法。

PS:如果确实需要基于索引的集合,则可以更改readAllLines的定义以返回List

答案 1 :(得分:0)

我已解决问题:

public String[] getZeichenListe(String dateiname) {
String str = "";
try {
    InputStream is = getAssets().open(dateiname);
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    String buffer = "";

    while ((buffer = br.readLine()) != null) str = buffer + ";" + str;
    is.close();
    br.close();

} catch (IOException e) {
    e.printStackTrace();
}
return str.split(";");

}

尽管我不太确定我认为问题是我只重新初始化了BufferedReader,但没有重新初始化InputStream。

相关问题