简体   繁体   中英

How to append and alter data in specific file locations

Good evening Stack Overflow! I am working on a project that resembles Windows Access Control Lists, and have run into an issue. I need to use files to keep track of who is in what group, so for instance, in my file, I want to have have this:

  • Administrators: admin, mike
  • Users: admin, mike, sarah, eric
  • Accounting: sarah, eric

I've been simply appending data onto the list, so it would be more like this:

  • Administrators: admin
  • Administrators: mike

I also need to be able to add things out of order, so for instance, if I added Admin to Admins, Sarah to Accounting, then Mike to Admins, is there a way to keep all of the data in order?

I was wondering how to solve this problem, to append data to specific locations so that it doesn't look like a train wreck.

Thanks!

You cannot append data directly into the file. You can read it all and change insert data into specific positions, using RandomAccessFile . Here is a nice tutorial on how to do so: http://tutorials.jenkov.com/java-io/randomaccessfile.html

Below is how you insert thing in the middle of a file that is loaded in memory:

// 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();

However, I would not follow this approach. Why don't you put everything in CSV files, read them using Java, put the content into a list, do whatever inserts, deletes and sorting you wish (sorting is alredy there for Strings), and then save the files into the the file system again?

You can use OpenCSV to read CSV files, and below is an example:

... 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]);
        }
      }
    }
  }
}

Following this approach, then in order to insert elements in the middle, or in the end of the list is a matter of using the data structure appropriately, and finally writing them to disk, alo using OpenCSV if you wish.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM