fork(12) 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. String[][] records = loadRecords();
  11.  
  12. Arrays.sort(records, new Comparator<String[]>() {
  13. @Override
  14. public int compare(String[] o1, String[] o2) {
  15. return o1[0].compareTo(o2[0]);
  16. }
  17. });
  18. saveRecords("/home/b/Desktop/sortedByName.txt", records);
  19.  
  20. Arrays.sort(records, new Comparator<String[]>() {
  21. @Override
  22. public int compare(String[] o1, String[] o2) {
  23. return o1[1].compareTo(o2[1]);
  24. }
  25. });
  26. saveRecords("/home/b/Desktop/sortedByNumber.txt", records);
  27.  
  28. Arrays.sort(records, new Comparator<String[]>() {
  29. @Override
  30. public int compare(String[] o1, String[] o2) {
  31. int c = Integer.compare(o1[2].length(), o2[2].length());
  32. if (c == 0) {
  33. c = o1[2].compareTo(o2[2]);
  34. }
  35. return c;
  36. }
  37. });
  38. saveRecords("/home/b/Desktop/sortedByScore.txt", records);
  39. }
  40.  
  41. static void saveRecords(String filepath, String[][] records) {
  42. try {
  43. try (FileOutputStream fos = new FileOutputStream(filepath)) {
  44. try (OutputStreamWriter osw = new OutputStreamWriter(fos)) {
  45. try (BufferedWriter bw = new BufferedWriter(osw)) {
  46. for (String[] columns : records) {
  47. bw.write(columns[0] + " " + columns[1] + " " + columns[2]);
  48. bw.newLine();
  49. }
  50. }
  51. }
  52. }
  53. } catch (IOException e) {
  54. throw new RuntimeException(e);
  55. }
  56. }
  57.  
  58. static String[][] loadRecords() {
  59. try {
  60. String[][] records = new String[20][];
  61. try (FileInputStream fis = new FileInputStream("/home/b/Desktop/data.txt")) {
  62. try (InputStreamReader isr = new InputStreamReader(fis)) {
  63. try (BufferedReader br = new BufferedReader(isr)) {
  64. for (int i = 0; i < 20; i++) {
  65. records[i] = br.readLine().split(" ");
  66. }
  67. return records;
  68. }
  69. }
  70. }
  71. } catch (IOException e) {
  72. throw new RuntimeException(e);
  73. }
  74. }
  75. }
  76.  
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty