【发布时间】:2015-05-26 20:53:30
【问题描述】:
我正在尝试编写和读取一个充满单词的文本文件并将其添加到 ArrayList。 ArrayList 稍后从程序的另一部分用于在 TextView 中显示文本。但是当我运行程序并打开它的特定部分时,什么都没有。 ArrayList 只是空的。我没有得到任何例外,但由于某种原因它不起作用。请帮帮我。
我的文件写入似乎没有问题:
TextView txt = (TextView)findViewById(R.id.testTxt);
safe = txt.getText().toString();
try {
FileOutputStream fOut = openFileOutput("test.txt", MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
try {
osw.write(safe);
osw.flush();
osw.close();
Toast.makeText(getBaseContext(), "Added to favorites", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException ex){
Log.e("Exception", "File write failed: ");
}
} catch (IOException e) {
Log.e("Exception", "File write failed: ");
}
但我认为问题在于文件读取。我做了一些“Log.d”,发现在 InputStreamReader 行之前一切正常:
public favHacks() {
testList = new ArrayList<String>();
try {
//Works fine till here
InputStreamReader inputStreamReader = new InputStreamReader(openFileInput("test.txt"));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
while ( (receiveString = bufferedReader.readLine()) != null )
{
testList.add(receiveString);
}
bufferedReader.close();
}
catch (FileNotFoundException ex) {
Log.d("login activity", "File not found: ");
} catch (IOException ex) {
Log.d("login activity", "Can not read file: ");
}
}
【问题讨论】:
-
你有什么问题?崩溃?然后发布日志。数据损坏?发布一个小文件示例——你期望什么,你得到什么。
-
编辑了我期望发生的事情。但就像我说的,我没有遇到任何崩溃或类似的事情。
-
您的 inputStreamReader 是否为空?
-
不要把 try/catch 放在 try/catch 中。我猜你正在使用
MODE_WORLD_READABLE,因为你正在做一些“hackish”并且基于你的方法“favHacks”。openFileInput是什么? -
哦,不,favHacks 只是一些东西的捷径,但我觉得这听起来很有趣,所以我让它这样。我实际上“解决”了我的问题,但现在我得到了 FileNotFoundException。
标签: android text-files inputstream fileinputstream inputstreamreader