JAVA第09次实验(IO流)

0.字节流与二进制文件

我的代码

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

class Student {
       private int id;
       private String name;
       private int age;
       private double grade;    
       public Student(){
           
       }
       public Student(int id, String name, int age, double grade) {
          this.id = id;
          this.setName(name);
          this.setAge(age);
          this.setGrade(grade);
      }
      public int getId() {
          return id;
      }
      public void setId(int id) {
          this.id = id;
      }
      public String getName() {
          return name;
      }
      public void setName(String name) {
          if (name.length()>10){
              throw new IllegalArgumentException("name's length should <=10 "+name.length());
          }
          this.name = name;
      }
      public int getAge() {
          return age;
      }
      public void setAge(int age) {
          if (age<=0){
              throw new IllegalArgumentException("age should >0 "+age);
          }
          this.age = age;
      }
      public double getGrade() {
          return grade;
      }
      public void setGrade(double grade) {
          if (grade<0 || grade >100){
              throw new IllegalArgumentException("grade should be in [0,100] "+grade);
          }
          this.grade = grade;
      }
      @Override
      public String toString() {
          return "Student [id=" + id + ", name=" + name + ", age=" + age + ", grade=" + grade + "]";
      }
      
  }
   public class Main {
          public static void main(String[] args)
          {
              
              String fileName="f:/student.txt";
              try(DataOutputStream dos=new DataOutputStream(new FileOutputStream(fileName)))
              {
                  Student[] stu=new Student[3];
                  stu[0]=new Student(1,"zhangsan",19,65.0);
                  stu[1]=new Student(2,"lisi",19,75.0);
                  stu[2]=new Student(3,"wangwu",20,85.0);
                  for(Student stu1:stu) {
                      dos.writeInt(stu1.getId());
                      dos.writeUTF(stu1.getName());
                      dos.writeInt(stu1.getAge());
                      dos.writeDouble(stu1.getGrade());
                  }
                  
              } catch (FileNotFoundException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
                  System.out.println("1");
              } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
                  System.out.println("2");
              }
              try(DataInputStream dis=new DataInputStream(new FileInputStream(fileName)))
              {
                  while(dis!=null) {
                      int id=dis.readInt();
                      String name=dis.readUTF();
                      int age=dis.readInt();
                      double grade=dis.readDouble();
                      Student stu=new Student(id,name,age,grade);
                      System.out.println(stu);
                  }
                  
                  
              } catch (FileNotFoundException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
                  System.out.println("3");
              } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
                 System.out.println("4");
             }
          }  
        }

我的总结

  使用字节流读写文本文件用FileInputStream和FileOutputStream,DataOutputStream是字节流与字符流之间的桥梁。

1.字符流与文本文件:使用PrintWriter(写),BufferedReader(读)

我的代码

  • (1)
public class Main {
        public static void main(String[] args) throws IOException
        {
            String FileName="f:/Students.txt";
            BufferedReader br = null;
            try {
                br = new BufferedReader(new InputStreamReader(new FileInputStream(FileName),"UTF-8"));
                String line = null;
                while((line=br.readLine())!=null)
                    System.out.println(line);
            } finally{
                if (br!=null){
                    br.close();
                }
            }
        }

    }
  • (2)
public static void ListreadStudents(String fileName){
            ArrayList<Student> StudentList=new ArrayList<Student>();
            BufferedReader br = null;
            try {
                br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName),"UTF-8"));
                while(br!=null) {
                    String line=br.readLine();
                    String[] stu=line.split("\\s+");
                    int id=Integer.parseInt(stu[0]);
                    String name=stu[1];
                    int age=Integer.parseInt(stu[2]);
                    double grade=Double.parseDouble(stu[3]);
                    Student Stu=new Student(id,name,age,grade);
                    StudentList.add(Stu);          
                }                
            } finally{
                if (br!=null){
                    br.close();
                }
            }
}
  • (3)
String FileName="f:Students.txt";
            PrintWriter pw=new PrintWriter(new OutputStreamWriter(new FileOutputStream(FileName,true),"UTF-8"));
            pw.print("4 wanger 21 90");
            pw.close();
  • (4)
String FileName="f:\Students.dat";
            try(
                    FileOutputStream fos=new FileOutputStream(FileName);
                    ObjectOutputStream oos=new ObjectOutputStream(fos))
                {
                    Student ts=new Student(5,"asd",14,60);
                    oos.writeObject(ts);
                }
                catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                try(
                    FileInputStream fis=new FileInputStream(FileName);
                    ObjectInputStream ois=new ObjectInputStream(fis))
                {
                    Student newStudent =(Student)ois.readObject();
                    System.out.println(newStudent);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

我的总结

 (1)直接打开会出现乱码,所以在读取前要把模式改为“UTF-8”;
 (2)BufferedReader类带有缓冲区,可以优先把一批数据读到缓冲区。所以后面的读取操作,是从缓冲区内获取,避免每次都是从数据    源读取数据进行字符编码转换。

2. 缓冲流(结合使用JUint进行测试)

我的代码

  • PrintWriter
String FILENAME = "test.txt";    
        double sum=0,aver;
        PrintWriter pw=null;
        try {
            pw = new PrintWriter(FILENAME);
            for(int i = 0;i<10000000;i++){//写入1千万行
            int r=new Random().nextInt(10);
            sum+=r;
            pw.println(r);
            //System.out.println(r);
        }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally{
            pw.close();
        }
        aver=sum/10000000;
        System.out.format("%.5f", aver);
    }
  • JUint
public class test {
    @Test
        public void test() {
        String FILENAME = "test.txt";
        long begin = System.currentTimeMillis();
        Scanner scanner=null;
        try {
            scanner = new Scanner(new File(FILENAME));
            while(scanner.hasNextLine()){//只是读出每一行,不做任何处理
                scanner.nextLine();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally{
            scanner.close();
        }
        long end = System.currentTimeMillis();
        System.out.println("last "+(end-begin));
        System.out.println("read using Scanner done");
    }
    @Test
    public void Bufftest() {
        String FILENAME = "test.txt";
        long begin = System.currentTimeMillis();
        BufferedReader br = null;
        try {
             br = new BufferedReader(new FileReader(new File(FILENAME)));
            while(br.readLine()!=null){};//只是读出,不进行任何处理
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("last "+(end-begin));
        System.out.println("read using BufferedReader done");
    }
}

我的总结

   在处理大量数据时,使用缓冲流BufferedReader比Scanner明显快很多。

3. 字节流之对象流

我的代码

public static void writeStudent(List<Student> stuList)
    {
        String fileName="f:/Students.dat";
        try (   FileOutputStream fos=new FileOutputStream(fileName);
                ObjectOutputStream ois=new ObjectOutputStream(fos))
        {
            ois.writeObject(stuList);
            
        } 
        catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
public static List<Student> readStudents(String fileName)
    {
        List<Student> stuList=new ArrayList<>();
        try (   FileInputStream fis=new FileInputStream(fileName);
                ObjectInputStream ois=new ObjectInputStream(fis))
        {
            stuList=(List<Student>)ois.readObject();
        } 
        catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return stuList;
    }

我的总结

   ObjectOutputStream、ObjectInputStream与FileInputStream、FileOuputStream放在一起使用时,可以对对象永久存储。其中ObjectOutputStream、ObjectInputStream是高级流。
posted on 2019-11-26 22:44  猜丁壳  阅读(146)  评论(0编辑  收藏  举报