[英]How to append and alter data in specific file locations
晚上好,堆棧溢出! 我正在一個類似於Windows訪問控制列表的項目,但是遇到了問題。 我需要使用文件來跟蹤誰在哪個組中,因此,例如,在我的文件中,我想擁有以下內容:
我一直只是將數據追加到列表中,所以更像是這樣:
我還需要能夠無序添加內容,例如,如果我將Admin添加到Admins,將Sarah添加到Accounting,然后將Mike添加到Admins,是否有辦法使所有數據保持順序?
我想知道如何解決此問題,將數據附加到特定位置,以免看起來像火車殘骸。
謝謝!
您不能將數據直接附加到文件中。 您可以使用RandomAccessFile
讀取所有內容並將插入數據更改到特定位置。 這是有關如何執行此操作的很好的教程: http : //tutorials.jenkov.com/java-io/randomaccessfile.html
以下是如何在裝入內存的文件中間插入東西:
// open file for reading and writing
RandomAccessFile file = new RandomAccessFile("c:\\data\\file.txt", "rw");
// go to a certain position
file.seek(200);
// write hello world in ths position
file.write("Hello World".getBytes());
// close file - this should be done in the finally clause
file.close();
但是,我不會遵循這種方法。 您為什么不將所有內容都放入CSV文件中,使用Java讀取它們,將內容放入列表中,進行所需的任何插入,刪除和排序操作(對字符串進行排序,然后將其保存)到文件中系統再次?
您可以使用OpenCSV讀取CSV文件,下面是一個示例:
... import java.util.*;
public class ParseCSV {
public static void main(String[] args) {
try {
//csv file containing data
String strFile = "MyCSvFile.csv";
CSVReader reader = new CSVReader(new FileReader(strFile));
String [] nextLine;
// list holding all elements - they can be later be maniulated
List<String> elements = new ArrayList<String>();
while ((nextLine = reader.readNext()) != null) {
for (int i = 0; i < nextLine.length;i++) {
elements.add(nextLine[i]);
}
}
}
}
}
按照這種方法,然后要在列表的中間或列表的末尾插入元素,需要適當地使用數據結構,最后將它們寫入磁盤,如果需要的話,也可以使用OpenCSV 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.