如何在java中编写文本文件的特定位置

问题描述:

问题是我有四个不同的数组列表。我想根据用户给定的输入插入特定数组列表类的数据。 我该怎么做?如何在java中编写文本文件的特定位置

import java.io.*; 
import java.util.*; 

public class acquaintances 
{ 
    public static void main(String args[]) 
    { 
    Arraylist<relative>re=new Arraylisrt<relative>(); 
    Arraylist<personalfriend> pf=new Arraylist<personalfriend>(); 
    Arraylist<casualfriend> cf=new Arraylist<casualfriend>(); 
    Arraylist<professionalfriend> prf=new Arraylist<professionalfriend>(): 

这些是不同的阵列列表。

Iwant写的顺序不同acquantances信息的文本文件

休闲朋友1

休闲FRIEND2相对

........

relative 2

......

personalfriend1

个人FRIEND2

个人friend3

...........

professionalfriend1

professionalfriend2

.... ..............

此外,如果我删除特定的细节。那么我应该如何从文件中删除特定

详细

 String name=null,number=null,email=null; 
    File file = new File("Readme.txt"); 
    if (!file.exists()) { 
      file.createNewFile(); 
     } 

    Scanner sc=new Scanner(System.in); 

    int ch=0,chu=0; 
    String jaff=null,baff=null; 
    FileWriter fw = new FileWriter(file.getAbsoluteFile()); 
    BufferedWriter bw = new BufferedWriter(fw); 

    String cmet_why=null,cinfo=null,cdate=null; 

    while(1) 
    { 
     System.out.println("Enter name,number,email of acquaintance"); 
     name=sc.nextLine(); 
     number=sc.nextLine(); 
     email=sc.nextLine(); 
     System.out.println("1.Create 2.Delete 3.Display 4. DisplayAll 5.Search); 
     ch=sc.nextInt(); 
     jaff=sc.nextLine(); 
     Switch(ch): 
     { 
      case 1: 
      { 
       System.out.println("1.Casual friend 2.relative 3.personal friend 4. Professional friend"); 
       chu=sc.nextInt(); 
       baff=sc.nextLine(); 
       if(chu==1) 
       { 
        System.out.println("Enter reasonto meet ,dateof meeting,info"); 
        cmet_why=sc.nextLine(); 
        cdate=sc.nextLine(); 
        cinfo=sc.nextLine(); 
        casualfriend cfriend=new casualfriend(name,number,email,cmet_why,cdate,cinfo); 

在这里,我添加了类对象,以休闲的好友列表

,我想将其写入文本文件中的位置。

问题在于它位于文本文件的中间。

在此之后,我必须写亲戚,个人朋友,专业朋友。由线

    cf.add(cfriend); 

       } 
      } 

     } 
    } 


} 

}

信息行

有不同开关的情况。我想按顺序写这些。

+1

删除文件,并以您喜欢的任何顺序从头开始重新编写更新的信息? –

+1

你的问题不是很清楚。你究竟需要什么?请注意,您不能简单地插入或删除文件中随机位置的文本。您必须将新数据写入另一个文件,然后重命名它。 – 5gon12eder

+1

谢谢。我明白了。 –

public static void writeWithRandmoAccessFile(String content, String filePath) { 

     try (RandomAccessFile randomAccessFile = new RandomAccessFile(new File(filePath), "rw")) { 

     // move the cursor to the end of the file 
     // you can move the cursor to any position inside the file or to write at random positions 
     randomAccessFile.seek(randomAccessFile.length());//random position 

     randomAccessFile.write(content.getBytes()); 

     // alternatively you can use randomAccessFile.writeChars(content) 
     // or randomAccessFile.writeUTF(content); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
}