爪哇.如何将文本附加到 file.txt 的顶部 [英] Java. How to append text to top of file.txt
问题描述
我需要通过 Java 在文本文件的开头添加文本.
I need to add text to beggining of text file via Java.
例如我有包含数据的 test.txt 文件:
For example I have test.txt file with data:
Peter
John
Alice
我需要添加(到文件顶部):
I need to add(to top of file):
Jennifer
应该是:
Jennifer
Peter
John
Alice
我有一部分代码,但是它将数据附加到文件末尾,我需要让它在文件顶部添加文本:
I have part of code, but It append data to end of file, I need to make It that added text to top of file:
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();
}
}
我已经试过了,但这只会从文件中删除所有数据,而不是插入任何文本:
I have tried this, but this only deletes all data from file and not insert any text:
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);
}
}
感谢您的帮助.
推荐答案
您可以使用 RandomAccessFile 使用seek(long position)
方法将光标seek到0th
位置,在开始写作之前.
You can use RandomAccessFile to and seek the cursor to 0th
position using seek(long position)
method, before starting to write.
如中所述这个线程
RandomAccessFile f = new RandomAccessFile(new File("yourFile.txt"), "rw");
f.seek(0); // to the beginning
f.write("Jennifer".getBytes());
f.close();
正如下面许多评论所指出的,这个解决方案从一开始就覆盖文件内容.要完全替换内容,可能需要删除和重写文件.
As pointed out below by many comments, this solution overwrites the file content from beginning. To completely replace the content, the File may have to be deleted and re-written.
这篇关于爪哇.如何将文本附加到 file.txt 的顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!