如何在java中编写文本文件的特定位置
问题是我有四个不同的数组列表。我想根据用户的输入插入特定数组列表类的数据。 我该怎么做如何在java中编写文本文件的特定位置,java,text-files,Java,Text Files,问题是我有四个不同的数组列表。我想根据用户的输入插入特定数组列表类的数据。 我该怎么做 import java.io.*; import java.util.*; public class acquaintances { public static void main(String args[]) { Arraylist<relative>re=new Arraylisrt<relative>(); Arraylist<pe
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>():
在这里,我将类对象添加到临时好友列表中
我想把它写到这个位置的文本文件中
问题是它在文本文件的中间。
在这之后,我不得不写信给亲戚、私人朋友、职业朋友
逐行输入信息
cf.add(cfriend);
}
}
}
}
}
}
有不同的开关箱。我想按顺序写这些内容。删除文件,然后用更新后的信息按您喜欢的顺序从头重写?您的问题不是很清楚。你到底需要什么?请注意,不能简单地从文件中的随机位置插入或删除文本。您必须将新数据写入另一个文件,然后将其重命名。谢谢。我理解它。如果要在现有文件中插入/删除,一种方法是使用
java.io.RandomAccessFile
。请注意,插入和删除操作需要移动文件中的其余数据。方法“RandomAccessFile.seek()
和RandomAccessFile.getFilePointer()
很有用。@5gon12eder-您声称必须将数据写入另一个文件才能插入/删除的说法是不正确的。
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();
}
}
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();
}
}