首页 > 解决方案 > 如何写入文件排序数组java

问题描述

如何编写一个保存已排序数组的构造函数,然后使用 getDatabase 之类的方法将其写入文件,该方法返回已传递已排序数组的对象。

数据库类:

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;
}

存储类:

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;
}

这些只是我拥有的代码片段。我正在尝试将排序后的数组写入文件,并且我知道它正在按年龄正确排序文件,但我不确定如何将其写入文件。

我主要有:

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

标签: java

解决方案


只关注基于年龄和描述的 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");
  }
}

给定以下输入:

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

该程序产生以下输出:

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

似乎只是为了排序而将这些数组编组到 Person 对象中是多余的。但是,如果您想这样做,将字段值数组转换为 Person 对象将非常容易。我会把它留给你。


推荐阅读