我在外部存储上的“.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;
}
我真的不知道如何解决这个问题并让这个方法适用于我的程序。 如果有人能帮助我,那就太好了。
答案 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());
}