【问题标题】:how to delete elements from both array list and text file in java?如何从java中的数组列表和文本文件中删除元素?
【发布时间】:2015-03-01 05:34:06
【问题描述】:

我有一个数组列表,它从文本文件中获取其元素,如果我从数组列表中删除一些元素,它们也应该从文件中删除,我该怎么做? 我在某处读到我应该使用临时文件,但我不知道该怎么做。

【问题讨论】:

    标签: java file arraylist io


    【解决方案1】:

    您要做的是将数组列表中的新元素复制到新文件中,或者您可以复制并替换原始文件中的数据,例如您有一个包含数据的文件并且您有一个数组与文件具有相同数据的列表,因此如果您更改数组列表中的元素,请再次复制并替换文件:

    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();
      } 
     }
    

    【讨论】:

      【解决方案2】:

      您应该有包装类来保存 ArrayList 并引用 File 。 在包装类中,您有 loaddelete 之类的方法。

      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 文件的结构.

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-07-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-14
        • 2018-01-08
        相关资源
        最近更新 更多