1. 程式人生 > 其它 >位元組流結合類,實現簡單錄入資訊,並在本地儲存

位元組流結合類,實現簡單錄入資訊,並在本地儲存

技術標籤:學習筆記java

/*
位元組流結合類,實現簡單錄入資訊,並在本地儲存

 */
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

public class Test {
    public static void main(String[] args) throws IOException {

        ArrayList<Student>
list = new ArrayList<>(); //建立"學生資訊"資料夾 File file = new File("F:\\學生資訊"); file.mkdirs(); //鍵盤錄入學生資訊 Scanner sc = new Scanner(System.in); for (int i = 0; i < 3; i++) { System.out.println("請輸入學生姓名:"); String name =
sc.next(); System.out.println("請輸入學生年齡:"); int age = sc.nextInt(); //將學生資訊新增到集合 list.add(new Student(name, age)); } //遍歷集合得到每個學生的基礎資訊 for (Student student : list) { String name = student.getName(); String age = Integer.
toString(student.getAge()); //建立以學生姓名命名的文字 String s = name + "--" + age; File file1 = new File(file, name + ".txt"); boolean newFile = file1.createNewFile(); System.out.println(name + "資訊建立" + newFile); //寫入學生資訊到對應TXT文字 FileOutputStream fos = new FileOutputStream(file1); fos.write(s.getBytes()); fos.close(); } } } 基本學生類![在這裡插入圖片描述](https://img-blog.csdnimg.cn/20201214222604766.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0l2ZW53Zg==,size_16,color_FFFFFF,t_70#pic_center) import java.util.Objects; public class Student { private String name; private int age; public Student() { } public Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Student student = (Student) o; return age == student.age && Objects.equals(name, student.name); } @Override public int hashCode() { return Objects.hash(name, age); } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; } } ![```](https://img-blog.csdnimg.cn/20201214222720290.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0l2ZW53Zg==,size_16,color_FFFFFF,t_70#pic_center)