简体   繁体   中英

How to write to file a sorted array java

How to write a constructor that holds the sorted array, Then write it to a file with a method like getDatabase that returns an object that has been passed the sorted array.

Database class:

public Person[] entry; // this needs to be an array that will hold the person obj each new entry to the array is added to the next avail pos in list

public Database(int capacity) {
    entry = new Person[capacity];
    size = 0;
}

public Person[] getDatabase() {
    return entry;
}

Storage Class:

public dataBase writeCommaSeparated(Database data) throws IOException {
    Database db = new Database();
    PrintStream writer = new PrintStream(file);
    if(file.exists()) {
        for(int i = 0; i < data.size; i++) {
            writer.println(data.get(i).toFile());
        }
    }
    writer.close();
    return db;
}

public dataBase read() throws IOException {
    Database db = new Database();
    Scanner scan = new Scanner(file);
    Person person;
    //check if file has data print selected data
    while(scan.hasNextLine()) {
        person = parsePerson(scan.nextLine());
        db.add(person);
    }
    scan.close();
    return db;
}

These are just snippets of the code that I have. I am trying to write a sorted array into a file, and I know that it is sorting the file by age correctly but I am not sure how to write it out to a file.

in main I have:

String fileLocation = File.separator + "Users" 
                        + File.separator + "USERNAME" 
                        + File.separator + "Desktop" 
                        + File.separator + "DataFile.txt";

FileStorage   fileStore  = new FileStorage(fileLocation);

FileData data  = fileStore.read(); // this invokes a method called read that reads the file

data.sort(); // sorts the file by age and prints out to the console the sorted age

fileSort.writeCommaSeparated(data); // writes to the file in a commaseparated way

Focusing on just the sorting of a csv file based on age and given your description, this was about the simplest solution that came to mind.

public class PersonDatabase {

  private ArrayList<String[]> people = new ArrayList();
  // Reads the given input file and loads it into an ArrayList of string arrays.
  public PersonDatabase(String inputFile) throws IOException {
    BufferedReader in = new BufferedReader(new FileReader(inputFile));
    for (String line = null; null != (line=in.readLine()); ) {
        people.add(line.split(",")); // convert csv string to an array of strings.
    }
    in.close();
  }

  private static final int AGE_COLUMN_INDEX=2; // Identifies the 'age' column

  // performs a numeric comparison on the 'age' column values.
  int compareAge(String[] a1, String[]a2) {
    return Integer.compare(
        Integer.parseInt(a1[AGE_COLUMN_INDEX]),             
        Integer.parseInt(a2[AGE_COLUMN_INDEX]));
  }
  // Sorts the list of people by age and writes to the given output file.
  public void writeSorted(String outputFile) throws IOException {
    PrintWriter out = new PrintWriter(new FileWriter(outputFile));
    people.stream()
            .sorted(this::compareAge)                          // sort by age
            .forEach(a->{
                Arrays.stream(a).forEach(s->out.print(s+",")); // print as csv
                out.println();
            });
    out.close();
  }

  public static void main(String[] args) throws IOException {
    PersonDatabase pdb = new PersonDatabase("persondb.in");
    pdb.writeSorted("persondb.out");
  }
}

Given the following input:

fred,flintstone,43,
barney,rubble,42,
wilma,flintstone,39,
betty,rubble,39,

This program produces the following output:

wilma,flintstone,39,
betty,rubble,39,
barney,rubble,42,
fred,flintstone,43,

It seemed like marshalling these arrays into Person objects just for the sake of sorting was overkill. However, if you wanted to do that, it would be pretty easy to turn an array of field values into a Person object. I'll leave that to you.

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