大多数应用程序都需要实现与设备之间的数据传输,例如键盘可以输入数据,显示器可以显示程序的运行结果等。在Java中,将这种通过不同输入输出设备(键盘,内存,显示器,网络等)之间的数据传输抽象表述为“流”,程序允许通过流的方式与输入输出设备进行数据传输。Java中的“流”都位于java.io包中,称为IO(输入输出)流。
通过对于学生数据文件的操作类(查询、增加、删除和修改)了解JAVA中对文件的操作
import java.io.*;
import java.util.ArrayList;
class Studen{
public String num;
public String name;
public String sex;
public Studen(String num,String name,String sex){
this.num=num;
this.name=name;
this.sex=sex;
}
}
class StudentDeal{
public Studen findStuByNum(String num){
Studen s1=null;
try{
//创建一个基于文件的字节输入流对象
FileReader fr = new FileReader("d:\\student.txt");
BufferedReader br = new BufferedReader(fr);
String temp=br.readLine();
while(temp!=null){
String[] infos=temp.split(",");
if(infos[0].equals(num)){
s1=new Studen(infos[0],infos[1],infos[2]);
break;
}
temp=br.readLine();
}
br.close();
fr.close();
}catch (FileNotFoundException ex){
System.out.println("文件未找到");
}catch(IOException ex){
System.out.println("文件读取错误");
}
return s1;
}
public Studen[] findStusByName(String name){
ArrayList<Studen> result = new ArrayList<Studen>();
try{
FileReader fr = new FileReader("d:\\student.txt");
BufferedReader br = new BufferedReader(fr);
String temp=br.readLine();
while(temp!=null){
String[] infos=temp.split(",");
if(infos[1].equals(name)){
result.add(new Studen(infos[0],infos[1],infos[2]));
}
temp=br.readLine();
}
br.close();
fr.close();
}catch (FileNotFoundException ex){
System.out.println("文件未找到");
}catch(IOException ex){
System.out.println("文件读取错误");
}
return (Studen[])result.toArray(new Studen[result.size()]);
}
public void addStudent(Studen stu){
if(!checkNumIsExist(stu.num)){
try{
FileWriter fw=new FileWriter("d:\\student.txt",true);
BufferedWriter bw=new BufferedWriter(fw);
StringBuffer str=new StringBuffer();
str.append(stu.num+",");
str.append(stu.name+",");
str.append(stu.sex);
bw.newLine();
//新增一行
bw.write(str.toString());
bw.close();
fw.close();
}catch (FileNotFoundException ex) {
}catch (IOException ex) {
}
}
}
}
public class Test10 {
public static void main(String[] args) {
StudentDeal deal=new StudentDeal();
Studen newstu=new Studen("078","丁二","男");
deal.addStudent(newstu);
deal.delStuByNum("023");
}
}