📄 8.5filerw.java
字号:
import java.io.*;
public class FileRW{
public static void main(String []args){
String file="student.dat";
Student s1=new Student();
Student s2=new Student(10,"张飞",16,'A',true);
try{
FileOutputStream fo=new FileOutputStream(file); //创建文件输出流对象
DataOutputStream out=new DataOutputStream(fo); //创建数据输出流对象
out.writeInt(s1.sno); //按照类型写文件
out.writeUTF(s1.name);
out.writeInt(s1.age);
out.writeChar(s1.grade);
out.writeBoolean(s1.sex);
out.writeInt(s2.sno);
out.writeUTF(s2.name);
out.writeInt(s2.age);
out.writeChar(s2.grade);
out.writeBoolean(s2.sex);
out.close();
fo.close();
System.out.println( "文件"+file+ "创建完毕!");
System.out.println("开始读取文件内容:");
FileInputStream fi=new FileInputStream(file); //创建文件输入流对象
DataInputStream in=new DataInputStream(fi); //创建数据输入流对象
for(int i=1;i<=2;i++) { //按照类型读取文件内容
int sno=in.readInt();
String sname=in.readUTF();
int age=in.readInt();
char grade=in.readChar();
boolean sex=in.readBoolean();
System.out.println(sno+"\t"+sname+"\t"+age+"\t"+grade+"\t"+sex);
}
in.close();
fi.close();
}catch(IOException e){ //捕获输入输出异常
System.out.println(e.toString()); }
}
}
class Student{
int sno;
String name;
int age;
char grade;
boolean sex;
public Student(){
this.sno=0;
this.name="未知";
this.age=0;
this.grade='C';
this.sex=true;
}
public Student(int sno,String name,int age,char grade, boolean sex){
if(sno>0) this.sno=sno;
this.name=name;
this.age=age;
this.grade=grade;
this.sex=sex;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -