繁体   English   中英

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

[英]How to write to file a sorted array 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

仅关注基于年龄的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对象将非常容易。 我留给你。

暂无
暂无

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

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