fork download
  1. package temp;
  2.  
  3. import java.io.*;
  4. import java.util.Arrays;
  5. import java.util.Comparator;
  6.  
  7. public class Test {
  8.  
  9. public static void main(String[] args) {
  10. Record[] records = loadRecords();
  11.  
  12. Arrays.sort(records, new Comparator<Record>() {
  13. @Override
  14. public int compare(Record o1, Record o2) {
  15. return o1.name.compareTo(o2.name);
  16. }
  17. });
  18. saveRecords("/home/b/Desktop/sortedByName.txt", records);
  19.  
  20. Arrays.sort(records, new Comparator<Record>() {
  21. @Override
  22. public int compare(Record o1, Record o2) {
  23. return o1.number.compareTo(o2.number);
  24. }
  25. });
  26. saveRecords("/home/b/Desktop/sortedByNumber.txt", records);
  27.  
  28. Arrays.sort(records, new Comparator<Record>() {
  29. @Override
  30. public int compare(Record o1, Record o2) {
  31. return Integer.compare(o1.score, o2.score);
  32. }
  33. });
  34. saveRecords("/home/b/Desktop/sortedByScore.txt", records);
  35. }
  36.  
  37. static void saveRecords(String filepath, Record[] records) {
  38. try {
  39. try (FileOutputStream fos = new FileOutputStream(filepath)) {
  40. try (OutputStreamWriter osw = new OutputStreamWriter(fos)) {
  41. try (BufferedWriter bw = new BufferedWriter(osw)) {
  42. for (Record record : records) {
  43. bw.write(record.name + " " + record.number + " " + record.score);
  44. bw.newLine();
  45. }
  46. }
  47. }
  48. }
  49. } catch (IOException e) {
  50. throw new RuntimeException(e);
  51. }
  52. }
  53.  
  54. static Record[] loadRecords() {
  55. try {
  56. Record[] records = new Record[20];
  57. try (FileInputStream fis = new FileInputStream("/home/b/Desktop/data.txt")) {
  58. try (InputStreamReader isr = new InputStreamReader(fis)) {
  59. try (BufferedReader br = new BufferedReader(isr)) {
  60. for (int i = 0; i < 20; i++) {
  61. String[] columns = br.readLine().split(" ");
  62. records[i] = new Record(columns[0], columns[1], Integer.parseInt(columns[2]));
  63. }
  64. return records;
  65. }
  66. }
  67. }
  68. } catch (IOException e) {
  69. throw new RuntimeException(e);
  70. }
  71. }
  72. }
  73.  
  74. class Record {
  75. String name;
  76. String number;
  77. int score;
  78.  
  79. Record(String name, String number, int score) {
  80. this.name = name;
  81. this.number = number;
  82. this.score = score;
  83. }
  84. }
  85.  
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty