爪哇岛。如何将文本追加到文件顶部.txt
我需要通过Java将文本添加到文本文件的开头。
例如,我有测试.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);
}
}
感谢您的帮助。