Android:从文件中读取字符串

时间:2014-03-10 16:46:10

标签: android input

我在外部存储上的“.txt”文件中读取字符串时遇到了一些麻烦。 我创建的方法不适用于我的程序,我需要一些帮助

private String readFromFile() {

String ret = "";

try {

final File configDir = new File(Environment.getExternalStorageDirectory(), "config");

    configDir.mkdir();

    InputStream inputStream = openFileInput(new File(configDir, "url.txt"));

    if ( inputStream != null ) {
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String receiveString = "";
        StringBuilder stringBuilder = new StringBuilder();

        while ( (receiveString = bufferedReader.readLine()) != null ) {
            stringBuilder.append(receiveString);
        }

        inputStream.close();
        ret = stringBuilder.toString();
    }
}
catch (FileNotFoundException e) {
    Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
    Log.e("login activity", "Can not read file: " + e.toString());
}

return ret;
}

我真的不知道如何解决这个问题并让这个方法适用于我的程序。 如果有人能帮助我,那就太好了。

1 个答案:

答案 0 :(得分:0)

使用FileReader代替InputStreamReader并更正configDir创建如下...

try {

    final File configDir = new File(Environment.getExternalStorageDirectory() + "/config");

    configDir.mkdir();

    File file = new File(configDir, "url.txt");

    if ( inputStream != null ) {

        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
        String receiveString = "";
        StringBuilder stringBuilder = new StringBuilder();

        while ( (receiveString = bufferedReader.readLine()) != null ) {
            stringBuilder.append(receiveString);
        }

        inputStream.close();
        ret = stringBuilder.toString();
    }
}
catch (FileNotFoundException e) {
    Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
    Log.e("login activity", "Can not read file: " + e.toString());
}