讀取文字檔案中Student.txt中內容(編號,姓名,成績)存放到學生物件中,並新增到集合物件,然後將分數低於等於80分的學生輸出到另外一個檔案中
阿新 • • 發佈:2018-12-25
讀取文字檔案中Student.txt中內容(編號,姓名,成績)存放到學生物件中,並新增到集合,然後將分數低於等於80分的學生輸出到另外一個檔案中
大概說一下,這裡面加上main函式一共有addlist()、outgrade()、creatstu()4個方法。
其中addlist為讀取檔案內容,然後賦值給學生物件並將學生物件新增到集合。
outgrade 方法為將成績低於等於80分的學生輸出到另外一個檔案裡。
creatstu為建立一個學生物件
讀寫檔案中的路徑我也沒有刪除,如果誰需要的話定義兩個檔案路徑就可以了。
附上兩個檔案的圖片,介紹寫的有點亂,誰需要的話就得稍微費點點時間了,大家共同學習,共同進步。加油加油加油!
“`
package Demo2;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Listdemo {
public static void main(String[] args) throws IOException { addlist(); outgrade(); } public static List<Student> list = new ArrayList<Student>(); public static void addlist() { File file = new File("C:\\Users\\Administrator\\Desktop\\abcde - 副本.txt"); try { BufferedReader br = new BufferedReader(new FileReader(file)); String str = null; while ((str = br.readLine()) != null) { String[] arr = str.split(","); Student stu = null; for (int i = 0; i < arr.length; i++) { stu = creatstu(); stu.setStuID(Integer.parseInt(arr[0])); stu.setName(arr[1]); stu.setAge(Integer.parseInt(arr[2])); stu.setGrade(Integer.parseInt(arr[3])); } list.add(stu); } } catch (NumberFormatException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } for (Student student : list) { System.out.println(student); } } public static Student creatstu() { Student stu = new Student(); return stu; } public static void outgrade() throws IOException { File file1 = new File("C:\\Users\\Administrator\\Desktop\\123.txt"); BufferedWriter br1 = null; br1 = new BufferedWriter(new FileWriter(file1)); for (Student student : list) { if (student.getGrade() <= 80) { br1.write(student.getStuID() + "," + student.getName() + "," + student.getAge() + "," + student.getGrade()); br1.flush(); br1.newLine(); } System.out.println(student); } br1.close(); }
}