[英]how to delete elements from both array list and text file in java?
我有一个arraylist,它从文本文件中获取其元素,如果我从arraylist中删除了一些元素,也应该从文件中删除它们,该怎么办? 我读过某个地方应该使用临时文件,但是我不知道该怎么做。
您应该具有包装器类来保存ArrayList
和对File
引用。 在包装器类中,您可以使用load
, delete
类的方法。
class <className>
{
List arrayList;
File file;
public void load(){
// Load the file content into Arraylist
}
public void delete(){
synchronized(this){
// delete the content from ArrayList and re-write the file
}
}
}
我刚刚给出了高水平。
您可以重写/修改文件/创建tmp文件,将org文件重命名为.bk,然后将tmp文件重命名为org文件-有很多方法可以实现,具体取决于您的要求以及org文件的结构。
您要做的是将数组列表中的新元素复制到新文件中,或者简单地,您可以复制并替换原始文件中的数据,例如,您有一个包含数据的文件,并且您有一个包含与文件相同的数据,因此,如果更改数组列表中的元素,请复制并再次替换文件:
class <className>
{
List arrayList;
File file;
//you should initialize the file and the arraylist first
public void reWrite()
{
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
for(Object object : arraylist)
{
bw.write(object);
}
bw.close();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.