Java 如何从文件中删除内容?

Java 如何从文件中删除内容?,java,file,Java,File,如何删除以附加模式添加到文件中的内容。此文件包含附加数据之前的大量记录 如何从该文件中删除jsonObject3和jsonObject4?请参考下面的代码 public class MainDemo { public static void main(String[] args) throws SQLException, ClassNotFoundException, IOException { String FileSeparato

如何删除以附加模式添加到文件中的内容。此文件包含附加数据之前的大量记录

如何从该文件中删除jsonObject3和jsonObject4?请参考下面的代码

public class MainDemo {
  public static void main(String[] args) throws SQLException, 
                      ClassNotFoundException, IOException {


    String FileSeparator=System.getProperty("file.separator");
    Path p=Paths.get("Dummy\\Downloads\\Test\\2018-12-28\\D");

    JSONObject jsonObject1 = new JSONObject();  
    jsonObject1.put("id",1);
    JSONObject jsonObject2 = new JSONObject();  
    jsonObject2.put("id",2);
    JSONObject jsonObject3 = new JSONObject();  
    jsonObject3.put("id",3);

    JSONObject jsonObject4 = new JSONObject();  
    jsonObject4.put("id",4);

    List<JSONObject> al=new ArrayList<>();

    al.add(jsonObject1);
    al.add(jsonObject2);
    al.add(jsonObject3);
    al.add(jsonObject4);

    for(JSONObject jsonObject:al) {
        String json=jsonObject.toString();      
        Files.write(
                Paths.get(p+FileSeparator+"Dummy.json"), 
                json.getBytes(), 
                StandardOpenOption.APPEND);

    }
    al.clear();
          // How do I remove the jsonObject3 and jsonObject4 from Dummy.json file

}
}
public类MainDemo{
公共静态void main(字符串[]args)引发SQLException,
ClassNotFoundException,IOException{
字符串FileSeparator=System.getProperty(“file.separator”);
路径p=Path.get(“虚拟\\下载\\测试\\2018-12-28\\D”);
JSONObject JSONObject 1=新的JSONObject();
jsonObject1.put(“id”,1);
JSONObject JSONObject 2=新的JSONObject();
jsonObject2.put(“id”,2);
JSONObject JSONObject 3=新的JSONObject();
jsonObject3.put(“id”,3);
JSONObject JSONObject 4=新的JSONObject();
jsonObject4.put(“id”,4);
List al=新的ArrayList();
新增(jsonObject1);
新增(jsonObject2);
新增(jsonObject3);
新增(jsonObject4);
for(JSONObject JSONObject:al){
字符串json=jsonObject.toString();
文件。写入(
get(p+FileSeparator+“Dummy.json”),
json.getBytes(),
标准OpenOption.APPEND);
}
al.clear();
//如何从Dummy.json文件中删除jsonObject3和jsonObject4
}
}

在这种情况下,您应该在分隔符字符串或“$”等符号的帮助下附加对象,然后可以读取文件,然后将读取的字符串存储在字符串变量中。 然后使用string.split(separatorString)获取数组中的对象。
然后删除所需的元素,并以覆盖模式从数组中重写文件中的数据。

首先不将
jsonObject3
jsonObject4
写入文件不是更容易(也更快)吗
for(JSONObject JSONObject:al.subList(0,2)){
我的要求是这样的。我可能还需要删除所有四个。您的文件有多大?它是否适合您的RAM?如果是这样,您可以将内容读取到字符串列表中,对其进行过滤(例如,通过流)然后覆盖现有文件。您可以使用RandomAccessFile setLength截断该文件。您需要知道要生成该文件的长度。感谢@PeterLawrey,我访问了RandomAccessFile的通道以截断并获取我正在操作的文件的位置。如果文件中包含多个对象,则为JSON现在已经有了一个非常好的分隔符。你的建议基本上是“将文件读入内存,将其拆分为内存中的一个数组,然后再将文件写出来”——这种解决方案不仅速度非常慢,而且对于那些非常大的文件也不起作用。