我有一个文字文件说:
Joan
Paul
Carren
我想要做的是在java
列表顶部添加Sean
我在stackoverflow上遇到了与此类似的另一个问题,但是,该答案会覆盖名字。
我现在拥有的是:
if (outputFile.exists()) {
try {
RandomAccessFile output = new RandomAccessFile(outputFileName, "rw");
output.seek(0);
output.write(headerComments.getBytes());
output.close();
} catch (IOException e) {
System.out.println("IO Exception");
}
}
答案 0 :(得分:0)
创建文件copy
。并且假设原始文件是original
。
Sean
写入文件copy
。original
中的每一行复制到文件copy
original
答案 1 :(得分:0)
此处Java. How to append text to top of file.txt已提出类似问题,但似乎尚未解决
您可能想尝试一下:
BufferedReader read= new BufferedReader(new FileReader(yourfilename));
ArrayList list = new ArrayList();
String dataRow = read.readLine();
while (dataRow != null){
list.add(dataRow);
dataRow = read.readLine();
}
FileWriter writer = new FileWriter(yourfilename); //same as your file name above so that it will replace it
writer.append(headerComments);
for (int i = 0; i < list.size(); i++){
writer.append(System.getProperty("line.separator"));
writer.append(list.get(i));
}
writer.flush();
writer.close();