我正在寻找清除 android 应用程序中的文本文件,然后将其重写为新的 ArrayList。我有问题的代码是
try{
bufferedWriter = new BufferedWriter(new OutputStreamWriter(openFileOutput("Account.txt", MODE_APPEND)));
bufferedWriter.flush();
for( int j = 0; j < ((ArrayHandler)getApplicationContext()).info.size(); j++)
{
if( text.equalsIgnoreCase(((ArrayHandler)getApplicationContext()).info.get(j).getAccountName()))
{
((ArrayHandler)getApplicationContext()).info.remove(j);
for( int k = 0; k < ((ArrayHandler)getApplicationContext()).info.size(); k++)
{
String account = ((ArrayHandler)getApplicationContext()).info.get(k).getAccountName();
String name = ((ArrayHandler)getApplicationContext()).info.get(k).getUserName();
String pass = ((ArrayHandler)getApplicationContext()).info.get(k).getPassword();
writeFileToStorage(account, name, pass);
}
}
}
}
catch(Exception err)
{
Toast.makeText(getBaseContext(), "Cannot flush file", Toast.LENGTH_SHORT).show();
}
运行此代码时,我总是得到 catch 子句。该文件被正确读入,但如果用户从 ArrayList 中删除某些内容,则该文件需要删除与 ArrayList 对应的项目。我的问题是,如何正确地写这个?
编辑 有问题的代码有效。但是,需要进行一些更改。这个:
bufferedWriter = new BufferedWriter(new OutputStreamWriter(openFileOutput("Account.txt", MODE_APPEND)));
需要改为
bufferedWriter = new BufferedWriter(new OutputStreamWriter(openFileOutput("Account.txt", MODE_PRIVATE)));
和这个:
bufferedWriter.close();
之后需要添加
bufferedWriter = new BufferedWriter(new OutputStreamWriter(openFileOutput("Account.txt", MODE_PRIVATE)));
bufferedWriter.flush();
看起来像这样:
bufferedWriter = new BufferedWriter(new OutputStreamWriter(openFileOutput("Account.txt", MODE_PRIVATE)));
bufferedWriter.flush();
bufferedWriter.close();
谢谢。希望这可以帮助某人。