简体   繁体   English

如何将文件写入排序数组Java

[英]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. 如何编写一个保存排序数组的构造函数,然后使用类似getDatabase的方法将其写入文件,该方法返回已通过排序数组的对象。

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. 仅关注基于年龄的csv文件排序并给出您的描述,这是想到的最简单的解决方案。

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. 仅仅出于排序的目的,将这些数组编组到Person对象中似乎就显得过分了。 However, if you wanted to do that, it would be pretty easy to turn an array of field values into a Person object. 但是,如果要这样做,将字段值数组转换为Person对象将非常容易。 I'll leave that to you. 我留给你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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