我需要通过 Java 将文本添加到文本文件的开头。
例如,我有带有数据的 test.txt 文件:
Peter
John
Alice
我需要添加(到文件顶部):
Jennifer
它应该是:
Jennifer
Peter
John
Alice
我有部分代码,但它将数据附加到文件末尾,我需要让它在文件顶部添加文本:
public static void irasymas(String irasymai){
try {
File file = new File("src/lt/test.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(irasymai+ "\r\n");
bw.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
我已经尝试过了,但这只会删除文件中的所有数据而不插入任何文本:
public static void main(String[] args) throws IOException {
BufferedReader reader = null;
BufferedWriter writer = null;
ArrayList list = new ArrayList();
try {
reader = new BufferedReader(new FileReader("src/lt/test.txt"));
String tmp;
while ((tmp = reader.readLine()) != null)
list.add(tmp);
OUtil.closeReader(reader);
list.add(0, "Start Text");
list.add("End Text");
writer = new BufferedWriter(new FileWriter("src/lt/test.txt"));
for (int i = 0; i < list.size(); i++)
writer.write(list.get(i) + "\r\n");
} catch (Exception e) {
e.printStackTrace();
} finally {
OUtil.closeReader(reader);
OUtil.closeWriter(writer);
}
}
谢谢你的帮助。