字节流、字符流的使用;打印流、数据流的使用;对象流序列化、反序列化;RandomAccessFile的使用;

一、字节流、字符流的使用练习:

      字节流在实现输出的时候需要用BufferedOutputStream点write(字符串.getBytes());而字符流直接BufferedWriter点write(字符串);即可。

      用Buffered类对象时,一定不要忘记加”类对象.flush( );

      Reader(读):读进程序中;   Writer(写):写到屏幕或文件上可以显式地看到。

Writer对应输出,Reader对应输入。

大体格式:

public class test00 {

       @Test

       public void test1() throws FileNotFoundException {

              File file1=new File("test.txt");

              FileOutputStream fos=new FileOutputStream(file1);

              BufferedOutputStream bos=new BufferedOutputStream(fos);

              String str="hello world!";

              bos.write(str.getBytes());

              bos.close();

       }

}

 

完整

package atguigu.exercise;



import java.io.BufferedOutputStream;

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;



import org.junit.Test;



public class testInputOutput {

      

       /*              第三问              */

      

       //字符流复制 test.txt 为 test1.txt

       @Test

       public void test4(){

              BufferedReader br=null;

              BufferedWriter bw=null;

              try {

                      br=new BufferedReader(new FileReader(new File("test.txt")));

                      bw=new BufferedWriter(new FileWriter(new File("test5.txt")));



                      char c[]=new char[50];      //数组用于存要读的文件中内容,数组长度代表了一次最多读多长的内容。

                      int len;

                      while((len=br.read(c))!=-1) {     //从br中读文本中的内容

                             bw.write(c, 0, len);             //把内容写入bw中,内容为数组c中从0号位开始到len号位结束的内容。

                      }

              } catch (FileNotFoundException e) {

                     // TODO Auto-generated catch block

                     e.printStackTrace();

              } catch (IOException e) {

                     // TODO Auto-generated catch block

                     e.printStackTrace();

              }finally {

                     if(bw!=null) {

                            try {

                                   bw.close();

                            } catch (IOException e) {

                                   // TODO Auto-generated catch block

                                   e.printStackTrace();

                            }

                     }

                     if(br!=null) {

                            try {

                                   br.close();

                            } catch (IOException e) {

                                   // TODO Auto-generated catch block

                                   e.printStackTrace();

                            }

                     }

              }

       }

      

      

      

       /*              第二问              */

        

       //使用字符流实现内容的读入

       @Test

       public void test3() {

              BufferedReader br=null;

              try {

                     br = new BufferedReader(new FileReader("test.txt"));

                     String str;

                     while((str=br.readLine())!=null) {

                            System.out.println(str);

                     }

              } catch (FileNotFoundException e) {

                     // TODO Auto-generated catch block

                     e.printStackTrace();

              } catch (IOException e) {

                     // TODO Auto-generated catch block

                     e.printStackTrace();

              }finally {

                     if(br!=null) {

                            try {

                                   br.close();

                            } catch (IOException e) {

                                   // TODO Auto-generated catch block

                                   e.printStackTrace();

                            }

                     }

              }

       }

      



      

       /*              第一问              */

      

       //实现一、使用字符流实现内容的输出

       @Test

       public void test2() {

              BufferedWriter bw=null;

              try {

                     bw = new BufferedWriter(new FileWriter(new File("test1.txt")));

                     String str="www.baidu.com";

                     bw.write(str);

                     bw.flush();

              } catch (IOException e) {

                     // TODO Auto-generated catch block

                     e.printStackTrace();

              }finally {

                     if(bw!=null) {

                            try {

                                   bw.close();

                            } catch (IOException e) {

                                   // TODO Auto-generated catch block

                                   e.printStackTrace();

                            }

                     }

              }

       }

      

      

      

       //实现二、使用字节流实现内容的输出(输出是程序里的内容输出到文件中去)

       @Test

       public void test1() throws FileNotFoundException {

              //3、定义一个Buffered类的对象为空

              BufferedOutputStream bos = null;

              try {

                     //1、定义File类的对象,可用于写入或读出文字

                     File file1=new File("test.txt");

                     //2、定义文件输出流,并将File类的对象作为形参。

                     FileOutputStream fos=new FileOutputStream(file1);

                     //4、将Buffered类的对象,将文件输出流的类对象作为形参。

                     bos = new BufferedOutputStream(fos);

//                  1、2、3、4可以合写为下面的一条语句

//                  BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(new File("test.txt")));

                     String str="hello world!";     //定义一段字符串

                     bos.write(str.getBytes());      //将字符串写入Buffered类的对象中

                     bos.flush();

              } catch (IOException e) {

                     // TODO Auto-generated catch block

                     e.printStackTrace();

              }finally {

                     //5、关闭Buffered流

                     if(bos!=null) {

                            try {

                                   bos.close();

                            } catch (IOException e) {

                                   // TODO Auto-generated catch block

                                   e.printStackTrace();

                            }

                     }

              }

       }

}

二、打印流_数据流的使用:

1、打印流:

package testOtherStream;



import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.PrintStream;



import org.junit.Test;



public class TestOtherStream {

//打印流:字节流:PrintStream ;字符流:PrintWriter

    //打印流相当于打印到指定的文件中了。

    @Test

    public void printStreamWriter() {

        FileOutputStream fos=null;

        try {

            fos=new FileOutputStream(new File("C:\\Users\\yts\\Desktop\\1042.txt"));

        } catch (FileNotFoundException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

        //创建打印输出流,设置为自动刷新模式(写入换行符或字节'\n'时都会刷新出输出缓冲区)

        PrintStream ps=new PrintStream(fos,true);//true表示自动刷新,相当于Buffered中的flush;

        if(ps!=null) { //把标准输出流(控制台输出)改成文件

            System.setOut(ps);//进行此之后,再进行System.out.println("...");就不是在控制台输出了,会到上面的文件中输出。

        }

        for(int i=0;i<25;i++) {    //输出ASCII码字符

            System.out.println((char) i);

            if(i%50==0) {  //每50个数据换一行

                System.out.println();  //换行

            }

        }

        ps.close();

    }

}

 

2、数据流:用于传输基本数据类型:

 

数据流:用来处理基本数据类型、String、字节数组的数据:DataInputStreamDataOutputStream;


 

package testOtherStream;



import java.io.DataInputStream;

import java.io.DataOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.PrintStream;



import org.junit.Test;



public class TestOtherStream {

    @Test

    public void testData1() {

        DataInputStream dis=null;

        try {

            dis=new DataInputStream(new FileInputStream(new File("test.txt")));

//          byte[] b=new byte[20];

//          int len;

//          while((len=dis.read(b))!=-1) {

//              System.out.println(new String(b,0,len));

//          }

            String str=dis.readUTF();

            System.out.println(str);

            boolean b=dis.readBoolean();

            System.out.println(b);

            long l=dis.readLong();

            System.out.println(l);

                  

        } catch (FileNotFoundException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        } catch (IOException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }finally {

            if(dis!=null) {

                try {

                   dis.close();

                } catch (IOException e) {

                   // TODO Auto-generated catch block

                   e.printStackTrace();

                }

            }

        }

    }

   

   

   

    //数据流:用来处理基本数据类型、String、字节数组的数据:DataInputStream、DataOutputStream;

    @Test

    public void testData(){

        DataOutputStream dos=null;

        try {

            FileOutputStream fos=new FileOutputStream("data.txt");

            dos=new DataOutputStream(fos);

           

            dos.writeUTF("我爱你,而你却不知道!");

            dos.writeBoolean(true);

            dos.writeLong(1432522344);

        } catch (FileNotFoundException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        } catch (IOException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

        finally {

            if(dos!=null) {

                try {

                   dos.close();

                } catch (IOException e) {

                   // TODO Auto-generated catch block

                   e.printStackTrace();

                }

            }

        }

    }

}

 

三、对象流的使用:

1、序列化与反序列化:

序列化实现的时内容存储到硬盘中,而反序列化实现的是将硬盘中的内容读取出来。

 

 

序列化是:ObjectOutputStream;反序列化:ObjectInputStream。

 

2、对象的序列化:(需要造一个实体类,用于实例化对象):

(1)、对象的序列化过程,将内存中的对象通过ObjectOutputStream转换为二进制,存储在硬盘中。

(2)、一个类如果想实现序列化要求:首先类一定是可序列化的,implements Serializable/(Externalizable);按理是应该重写接口的抽象方法,此接口中无抽象方法。

(3)、存进 :对象的序列化过程,将内存中的对象通过ObjectOutputStream转换为二进制,存储在硬盘中。

          获取:对象的反序列化过程,将硬盘中的文件通过ObjectInputStream转换为相应的对象

(4)、

要实现序列化必须要有一个类实现序列化:

 * 1、要求此类是可序列化的,实现Serializable接口

 * 2、要求类的属性同样的要实现Serislizable接口

 * 3、提供一个版本号:private static final long serialVersionUID

 * 4、如果类中的属性(即变量)用static或transient修饰,不可实现序列化。

3、全部的代码(类及实例化与反实例化的代码):

package testOtherStream;



import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.io.Serializable;



import org.junit.Test;



public class testObjectStream {

      //获取:对象的反序列化过程,将硬盘中的文件通过ObjectInputStream转换为相应的对象

      @Test

      public void testObjectInputStream() {

                  ObjectInputStream ois=null;

                  try {

                       ois = new ObjectInputStream(new FileInputStream("person.txt"));

                       Person p1=(Person)ois.readObject();

                       System.out.println(p1);

                       Person p2=(Person)ois.readObject();

                       System.out.println(p2);

                  } catch (ClassNotFoundException e) {

                       // TODO Auto-generated catch block

                       e.printStackTrace();

                  } catch (FileNotFoundException e) {

                       // TODO Auto-generated catch block

                       e.printStackTrace();

                  } catch (IOException e) {

                       // TODO Auto-generated catch block

                       e.printStackTrace();

                  }finally {

                       if(ois!=null) {

                             try {

                                   ois.close();

                             } catch (IOException e) {

                                   // TODO Auto-generated catch block

                                   e.printStackTrace();

                             }

                       }

                  }


      }

     

      //存进:对象的序列化过程,将内存中的对象通过ObjectOutputStream转换为二进制,存储在硬盘中。

      @Test

      public void testObjectOutputStream() {

            Person p1=new Person("小米",23,new Pet("牛牛"));

            Person p2=new Person("红米",21,new Pet("花花"));

            ObjectOutputStream oos=null;

            try {

                  oos=new ObjectOutputStream(new FileOutputStream("person.txt"));

                 

                  oos.writeObject(p1);

                  oos.flush();

                  oos.writeObject(p2);

                  oos.flush();

            } catch (FileNotFoundException e) {

                  // TODO Auto-generated catch block

                  e.printStackTrace();

            } catch (IOException e) {

                  // TODO Auto-generated catch block

                  e.printStackTrace();

            }finally {

                  if(oos!=null) {

                       try {

                             oos.close();

                       } catch (IOException e) {

                             // TODO Auto-generated catch block

                             e.printStackTrace();

                       }

                  }

            }

      }

}



/*

 * 要实现序列化的类:

 * 1、要求此类是可序列化的,实现Serializable接口

 * 2、要求类的属性同样的要实现Serislizable接口

 * 3、提供一个版本号:private static final long serialVersionUID

 * 4、如果类中的属性(即变量)用static或transient修饰,不可实现序列化。

 * */

class Person implements Serializable{

      private static final long serialVersionUID=14536537237L;

//  static String name;

//  transient int age;

      String name;

      int age;

      Pet pet;

      public Person(String name, int age,Pet pet) {

            this.name = name;

            this.age = age;

            this.pet=pet;

      }

      @Override

      public String toString() {

            return "Person [name=" + name + ", age=" + age + ", pet=" + pet + "]";

      }

}

//Pet在类Person中是属性,类的属性也必须是可序列化的。

class Pet implements Serializable{

      String name;

      public Pet(String name) {

            this.name=name;

      }

}

 

四、RandomAccessFile的使用:

 

 

package testOtherStream;



import java.io.File;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.io.RandomAccessFile;



import org.junit.Test;



/*

 * RandomAccessFile:支持随机访问

 *  1、既可以充当一个输入流,也可以充当一个输出流

 *  2、支持从文件的开头读取写入

 *  3、支持从任意位置的读取、写入(插入)

 * */

public class TestRandomAccessFile {

       //插入操作,相比较于testRandomAccessFile3,更通用

       @Test

       public void testRandomAccessFile4() {

              RandomAccessFile raf=null;

              try {

                     raf=new RandomAccessFile(new File("hello1.txt"),"rw");

                     //实现的是覆盖的效果,而不是插入的效果

                     raf.seek(4);

                     byte[] b=new byte[10];

                     int len;

                     StringBuffer sb=new StringBuffer();

                    

                     while((len=raf.read(b))!=-1) {

                            sb.append(new String(b,0,len));

                     }

                     raf.seek(4);

                     raf.write("xy".getBytes());

                     raf.write(sb.toString().getBytes());

              } catch (FileNotFoundException e) {

                     // TODO Auto-generated catch block

                     e.printStackTrace();

              } catch (IOException e) {

                     // TODO Auto-generated catch block

                     e.printStackTrace();

              }finally {

                     if(raf!=null) {

                            try {

                                   raf.close();

                            } catch (IOException e) {

                                   // TODO Auto-generated catch block

                                   e.printStackTrace();

                            }

                     }

              }

       }

      

      

      

       //实现插入的效果

       @Test

       public void testRandomAccessFile3() {

              RandomAccessFile raf=null;

              try {

                     raf=new RandomAccessFile(new File("hello1.txt"),"rw");

                     //实现的是覆盖的效果,而不是插入的效果

                     raf.seek(4);

                     String str=raf.readLine();

//                  long l=raf.getFilePointer();

//                  System.out.println(l);

                     raf.seek(4);

                     raf.write("xy".getBytes());

                     raf.write(str.getBytes());

                    

              } catch (FileNotFoundException e) {

                     // TODO Auto-generated catch block

                     e.printStackTrace();

              } catch (IOException e) {

                     // TODO Auto-generated catch block

                     e.printStackTrace();

              }finally {

                     if(raf!=null) {

                            try {

                                   raf.close();

                            } catch (IOException e) {

                                   // TODO Auto-generated catch block

                                   e.printStackTrace();

                            }

                     }

              }

       }

      

      

       //实现的是覆盖的效果,而不是插入的效果

       @Test

       public void testRandomAccessFile2() {

              RandomAccessFile raf=null;

              try {

                     raf=new RandomAccessFile(new File("hello1.txt"),"rw");

                     //实现的是覆盖的效果,而不是插入的效果

                     raf.seek(3);

                     raf.write("xy".getBytes());

                    

              } catch (FileNotFoundException e) {

                     // TODO Auto-generated catch block

                     e.printStackTrace();

              } catch (IOException e) {

                     // TODO Auto-generated catch block

                     e.printStackTrace();

              }finally {

                     if(raf!=null) {

                            try {

                                   raf.close();

                            } catch (IOException e) {

                                   // TODO Auto-generated catch block

                                   e.printStackTrace();

                            }

                     }

              }

             

             

       }

      

       @Test

       public void testRandomAccessFile1() {

              RandomAccessFile raf1=null;

              RandomAccessFile raf2=null;

              try {

                     raf1 = new RandomAccessFile(new File("hello.txt"),"r");

                     raf2 = new RandomAccessFile(new File("hello1.txt"),"rw");

                    

                     byte[] b=new byte[20];

                     int len;

                     while((len=raf1.read(b))!=-1) {

                            raf2.write(b,0,len);

                     }

              } catch (FileNotFoundException e) {

                     // TODO Auto-generated catch block

                     e.printStackTrace();

              } catch (IOException e) {

                     // TODO Auto-generated catch block

                     e.printStackTrace();

              }finally {

                     if(raf1!=null) {

                            try {

                                   raf1.close();

                            } catch (IOException e) {

                                   // TODO Auto-generated catch block

                                   e.printStackTrace();

                            }

                     }

                     if(raf2!=null) {

                            try {

                                   raf2.close();

                            } catch (IOException e) {

                                   // TODO Auto-generated catch block

                                   e.printStackTrace();

                            }

                     }

              }

       }

}

 

五、IO流的练习

 

 

 

自己编写的Scanner类的功能:

package atguigu.exercise;



import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;



public class MyInput {

    public String nextString() {

        InputStreamReader isr=new InputStreamReader(System.in);

        BufferedReader br=new BufferedReader(isr);

        String str=null;

        try {

            str=br.readLine();

        } catch (IOException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

        return str;

    }

    public int nextInt() {

        return Integer.parseInt(nextString());

    }

    public boolean nextBoolean() {

        return Boolean.parseBoolean(nextString());

    }

    public static void main(String[] args) {

        MyInput i=new MyInput();

        System.out.println("请输入一个:");

        String str=i.nextString();

        System.out.println(str);

//      int j=i.nextInt();

//      System.out.println(1+j);

    }

   

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值