Java文件操作,文件储存并读取类,数组等信息。实现学生用户信息储存与读取。使用FileWriter,BufferedWriter和Scanner类

        本文主要介绍使用FileWriter类和BufferedWriter类对文件进行字符串的写入操作,以及使用Scanner类实现对文件的读取操作,最终实现自定义类的属性储存和读取,希望能对同学们有帮助,如有不足还请多多指出

目录

1.测试定义学生类并储存如文件

2.使用Scanner类面向文件读取学生信息

3.总结


·使用编译器:

 

1.测试定义学生类并储存如文件

· 测试学生类定义(这里为了便于储存与使用,使用的全是字符串格式):

public class Student
{
    String id ;
    String name ;
    String age ;

    public Student()
    {}
    public Student( String id , String name , String age )     //有参构造方便后续
    {
        this.id = id ;
        this.name = name ;
        this.age = age ;
    }
}

·主函数代码如下:


import java.util.Scanner ;
import java.io.* ;


public class Main {
    public static void main(String[] args)
    {
        File file = new File( "D:\\系统默认\\桌面\\Data.txt" ) ;//打开文件
        FileWriter fileWriter = null ;
        BufferedWriter bufferedWriter = null ;  //FileWriter和BufferedWriter的初始化需要监听,此处只定义不初始化

        Scanner sc = null ; //同上
        Student[] stu = new Student[3] ;

        stu[0] = new Student( "001" , "喜羊羊" , "6" ) ;
        stu[1] = new Student( "002" , "懒羊羊" , "6" ) ;
        stu[2] = new Student( "007" , "灰太狼" , "20" ) ;

        try
        {
            fileWriter = new FileWriter( file ) ;
            bufferedWriter = new BufferedWriter( fileWriter ) ;

           for( int i = 0 ; i < stu.length ; i ++ )    //将学生类全部写入文件,bufferWirter可直接写入字符串,支持中文
            {
                bufferedWriter.write( stu[i].id ) ;
                bufferedWriter.write( " " ) ;
                bufferedWriter.write( stu[i].name ) ;
                bufferedWriter.write( " " ) ;
                bufferedWriter.write( stu[i].age );
                bufferedWriter.write( " " ) ;

                bufferedWriter.newLine() ;  //每输入一个学生都另起一行
            }
        }
        catch( Exception e )
        {
            System.out.println( "Error." ) ;
        }
        finally
        {
            try
            {

                bufferedWriter.close(); //随手关闭文件,此处注意关闭顺序不能错误
                fileWriter.close();
            }
            catch( IOException ioe )
            {

            }

        }
    }
}

·运行结果,正常运行后相应文件的内容:

 ·则文件储存代码部分正常,这部分需要注意文件的关闭顺序错误的话不会报错,但也无法储存任何信息。

2.使用Scanner类面向文件读取学生信息

·Student类没有改变,主函数代码如下:


import java.util.Scanner ;
import java.io.* ;


public class Main {
    public static void main(String[] args)
    {
        File file = new File( "D:\\系统默认\\桌面\\Data.txt" ) ;  //打开文件

        Scanner sc = null ;
        Student[] stu = new Student[3] ;

        try
        {
            sc = new Scanner( file ) ;

            for( int i = 0 ; i < stu.length ; i ++ )
            {
                stu[i] = new Student( sc.next() , sc.next() , sc.next() ) ; //注意此处即使不使用有参构造来读取信息,也要进行一次无参构造的初始化
            }
            System.out.println( "ID\t名字\t年龄\t" ) ;
            for( int i = 0 ; i < stu.length ; i ++ )
            {
                System.out.println( stu[i].id + "\t" + stu[i].name + "\t" + stu[i].age );
            }



        }
        catch( Exception e )
        {
            System.out.println( "Error." ) ;
        }
        finally
        {
            try
            {
                sc.close();
            }
            catch ( Exception e )
            {

            }
        }
    }
}

·如过读取正常,则运行结果如下:

"D:\IntelliJ IDEA Community Edition 2023.1.2\SDK\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2023.1.2\lib\idea_rt.jar=59525:D:\IntelliJ IDEA Community Edition 2023.1.2\bin" -Dfile.encoding=UTF-8 -Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8 -classpath "D:\IntelliJ IDEA Community Edition 2023.1.2\Programme\Experiment_1\out\production\Experiment_1" Main
ID	名字	年龄	
001	喜羊羊	6
002	懒羊羊	6
007	灰太狼	20

Process finished with exit code 0

由此便实现了我们今天要做的所有功能。

3.总结

        嗯...其实没什么好总结的,如果你不明白FileWriter类的操作方法可以去CSDN上看一看别的大大的文章,当然其实只要会用就行。try的作用就是字如其名就是监听报错的作用,欢迎大家一起交流讨论,有错误的地方欢迎指出。

  • 6
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
以下是一个简单的Java学生实现,包括从键盘输入学生信息、将学生信息到指定文本文件中、从文本文件读取特定学生信息、以及实现学生信息的增加、删除、修改、插入等操作。 ```java import java.io.*; import java.util.*; public class Student { private String name; private int age; private String gender; private String department; private String id; // 构造方法 public Student(String name, int age, String gender, String department, String id) { this.name = name; this.age = age; this.gender = gender; this.department = department; this.id = id; } // 无参构造方法 public Student() {} // toString方法 public String toString() { return "姓名:" + name + ",年龄:" + age + ",性别:" + gender + ",所在系:" + department + ",学号:" + id; } // 从键盘输入学生信息 public static Student inputStudent() { Scanner sc = new Scanner(System.in); System.out.print("请输入学生姓名:"); String name = sc.nextLine(); System.out.print("请输入学生年龄:"); int age = sc.nextInt(); sc.nextLine(); System.out.print("请输入学生性别:"); String gender = sc.nextLine(); System.out.print("请输入学生所在系:"); String department = sc.nextLine(); System.out.print("请输入学生学号:"); String id = sc.nextLine(); return new Student(name, age, gender, department, id); } // 将学生信息到指定文本文件中 public static void saveStudentToFile(Student student, String filePath) { try { FileWriter fw = new FileWriter(filePath, true); BufferedWriter bw = new BufferedWriter(fw); bw.write(student.toString()); bw.newLine(); bw.close(); fw.close(); System.out.println("学生信息已保到" + filePath + "文件中。"); } catch (IOException e) { e.printStackTrace(); } } // 从文本文件读取特定学生信息 public static List<Student> readStudentFromFile(String filePath, String id) { List<Student> students = new ArrayList<>(); try { FileReader fr = new FileReader(filePath); BufferedReader br = new BufferedReader(fr); String line; while ((line = br.readLine()) != null) { String[] fields = line.split(","); if (fields[4].equals(id)) { students.add(new Student(fields[0].substring(3), Integer.parseInt(fields[1].substring(4)), fields[2].substring(3), fields[3].substring(5), fields[4].substring(4))); } } br.close(); fr.close(); } catch (IOException e) { e.printStackTrace(); } return students; } // 实现学生信息的增加、删除、修改、插入等操作 public static void main(String[] args) { Scanner sc = new Scanner(System.in); List<Student> students = new ArrayList<>(); String filePath = "students.txt"; System.out.println("请选择操作:1.添加学生信息 2.删除学生信息 3.修改学生信息 4.插入学生信息 5.查询学生信息"); int choice = sc.nextInt(); switch (choice) { case 1: System.out.println("请输入要添加的学生信息:"); Student student = inputStudent(); students.add(student); saveStudentToFile(student, filePath); break; case 2: System.out.println("请输入要删除的学生学号:"); String deleteId = sc.next(); Iterator<Student> iter = students.iterator(); while (iter.hasNext()) { Student s = iter.next(); if (s.id.equals(deleteId)) { iter.remove(); break; } } break; case 3: System.out.println("请输入要修改的学生学号:"); String modifyId = sc.next(); for (int i = 0; i < students.size(); i++) { Student s = students.get(i); if (s.id.equals(modifyId)) { System.out.println("请输入修改后的学生信息:"); Student modifiedStudent = inputStudent(); students.set(i, modifiedStudent); break; } } break; case 4: System.out.println("请输入要插入的学生位置:"); int insertIndex = sc.nextInt(); System.out.println("请输入要插入的学生信息:"); Student insertedStudent = inputStudent(); students.add(insertIndex, insertedStudent); break; case 5: System.out.println("请输入要查询的学生学号:"); String searchId = sc.next(); List<Student> searchedStudents = readStudentFromFile(filePath, searchId); if (searchedStudents.size() == 0) { System.out.println("未找到学号为" + searchId + "的学生信息。"); } else { for (Student s : searchedStudents) { System.out.println(s); } } break; default: System.out.println("输入有误,请重新选择操作。"); break; } } } ``` 在上述代码中,我们通过一个简单的菜单来实现学生信息的增加、删除、修改、插入等操作。具体来说: - 当用户选择1时,程序会从键盘输入学生信息,并将其保到指定的文本文件中。 - 当用户选择2时,程序会从键盘输入要删除的学生学号,并在学生列表中查找该学生,如果找到则删除该学生信息。 - 当用户选择3时,程序会从键盘输入要修改的学生学号,并在学生列表中查找该学生,如果找到则从键盘输入修改后的学生信息,并将其更新到学生列表中。 - 当用户选择4时,程序会从键盘输入要插入的学生位置(索引),并从键盘输入要插入的学生信息,然后将其插入到学生列表中。 - 当用户选择5时,程序会从键盘输入要查询的学生学号,并从指定的文本文件中查找该学生信息,并输出到控制台。 需要注意的是,上述代码中的学生信息到文本文件中的格式为: ``` 姓名:XXX,年龄:XX,性别:XXX,所在系:XXX,学号:XXXXX ``` 因此,在从文本文件读取学生信息时,我们需要按照这个格式进行解析。另外,为了方便起见,我们在程序中使用Java集合来管理学生列表,而不是使用数组等数据结构。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值