Java IO读取文件的不同写法
发表于|更新于
|浏览量:
定义一个工具函数用于从文件读取所有学生信息,创建学生数组。
要求:
1 2 3 4 5 6 7 8 9
| public class Student { public static Student[] readFromFile(String path, int num) { } }
|
写法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| public static Student[] readFromFile(String path, int num) { Student[] students = new Student[num]; try (BufferedReader br = new BufferedReader(new FileReader(path))) { String line; int index = 0; while ((line = br.readLine()) != null && index < num) { String[] parts = line.split(","); if (parts.length == 3) { String name = parts[0].trim(); int age = Integer.parseInt(parts[1].trim()); String grade = parts[2].trim(); students[index++] = new Student(name, age, grade); } } } catch (IOException e) { System.err.println("Error reading file: " + e.getMessage()); } return students; }
|
尝试用Files和Paths读取文件,实现读取文件的功能。
要求:
1 2 3 4 5 6 7 8
| public class Student { public static Student[] readFromFile(String path, int num) { } }
|
写法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| public static Student[] readFromFile(String path, int num) { Student[] stu = new Student[0]; try { List<String> lines = Files.readAllLines(Paths.get(path)); stu = new Student[Math.min(num,lines.size())]; int index = 0;
for (String line : lines) { if (index >= num) break; String[] parts = line.split(","); String id = parts[0]; int scoreA = Integer.parseInt(parts[1]); int scoreB = Integer.parseInt(parts[2]); int scoreC = Integer.parseInt(parts[3]); stu[index] = new Student(id, scoreA, scoreB, scoreC); index++; } } catch (IOException e) { System.out.println(e); } return stu; }
|
排序函数
1 2 3 4 5 6
| public class Student { public static void sortByTotalScore(Student[] s) { Arrays.sort(s, c); } }
|
附上要求的Comparator接口实现
1 2 3 4 5 6 7
| public static final Comparator<Student> c = new Comparator<Student>() { @Override public int compare(Student s1, Student s2) { return Double.compare(s2.getTotalScore(), s1.getTotalScore()); } };
|
lambda表达式的简写:
1 2 3
| public static void sortByTotalScore(Student[] s) { Arrays.sort(s, Comparator.comparingInt(x -> x.totalScore())); }
|