天天看点

JavaSE——IO流

JavaSE——IO流

    • 流的分类
    • 节点流的使用(字符流)
    • 处理流的使用
      • (buffered字节流)
      • 转换流
    • 其他流
      • 标准输入输出流
      • 打印流
      • 数据流
      • 对象流
      • 随机存取文件流

流的分类

按操作数据单位分为:字节流(非文本)和字符流(文本数据)

按数据的流向分为:输入流和输出流

按流的角色分为:节点流和处理流

JavaSE——IO流
JavaSE——IO流
JavaSE——IO流

节点流的使用(字符流)

  1. 字符流的读入操作
public class test{
    public static void main(String[] args)  {
        FileReader fr = null;
        try {
            //1.实例化File类的对象,指明需要操作的文件
            File file = new File("hello.txt");
            //2.提供具体的流
            fr = new FileReader(file);
            //3.数据的读入
            int data;
            while((data=fr.read())!=-1){
                System.out.print((char)data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //4.流的关闭操作
            try {
            if(fr!=null) fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
           
FileReader fr=null;
try {
    File file = new File("hello.txt");
    fr = new FileReader(file);
    char[] cbuf=new char[5];
    int len;
    while((len=fr.read(cbuf))!=-1){
//                for(int i=0;i<cbuf.length;i++){
//                    System.out.println(cbuf[i]);
//                }//错误写法
//                for(int i=0;i<len;++i){
//                    System.out.print(cbuf[i]);
//                }//正确写法1
        String s = new String(cbuf, 0, len);
        System.out.print(s);
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if(fr!=null) {
        try {
            fr.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
}
           
  1. 字符流的写出操作
//1.提供file类
    File file = new File("hello.txt");
//2.提供FileWriter对象,用于数据的写出
FileWriter fw = new FileWriter(file,true);//第二个boolean类型表示是否追加
//3.写出操作
fw.write("I have a dream\t");
//4.流资源的关闭
fw.close();
           
File src = new File("Hello.txt");
File des = new File("Hello1.txt");
FileReader srcR = new FileReader(src);
FileWriter desW = new FileWriter(des,true);
char[] cbuf = new char[5];
int len;
while((len=srcR.read(cbuf))!=-1){
//            for(int i=0;i<len;++i){
//                desW.write(cbuf[i]);
//            }
   String s = new String(cbuf, 0, len);
   desW.write(s);
}
srcR.close();
desW.close();
           

处理流的使用

处理流关闭,内部流自动关闭

(buffered字节流)

public static void main(String[] args) throws IOException {
      File src = new File("hello.txt");
      File des = new File("Hello1.txt");
      FileInputStream fis = new FileInputStream(src);
      FileOutputStream fos = new FileOutputStream(des,true);
      BufferedInputStream bis = new BufferedInputStream(fis);
      BufferedOutputStream bos = new BufferedOutputStream(fos);

      byte[] buf = new byte[10];
      int len;
      while((len= bis.read(buf))!=-1){
          bos.write(buf,0,len);
      }

      bis.close();
      bos.close();
      //关闭外层流的同时,内层流也会被关闭,所以可以省略
      fis.close();
      fos.close();
  }
           

转换流

JavaSE——IO流

InputStreamReader:将一个字节的输入流转换为字符的输入流 解码

OutputStreamWriter:将一个字符的输出流转换为字节的输出流 编码

public static void main(String[] args) throws IOException {
        File file = new File("hello.txt");
        FileInputStream fis = new FileInputStream(file);
        //参数2是字符集,取决于存储的时候使用的是什么字符集
        InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
        char[] cbuf = new char[20];
        int len;
        while((len=isr.read(cbuf))!=-1){
            String s = new String(cbuf,0,len);
            System.out.print(s);
        }
        isr.close();
    }
           
//复制操作
File src = new File("hello.txt");
File des = new File("Hello1.txt");
FileInputStream fis = new FileInputStream(src);
FileOutputStream fos = new FileOutputStream(des);
InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
OutputStreamWriter osw = new OutputStreamWriter(fos,"gbk");
char[] cbuf = new char[20];
int len;
while((len=isr.read(cbuf))!=-1){
   osw.write(cbuf,0,len);
}
isr.close();
osw.close();
           

其他流

标准输入输出流

System.in:InputStream类型

System.out:PrintStream类型

System.setIn(InputStream is)、System.setOut(PrintStream ps):重新指定

public static void main(String[] args){
    //输入字符串变成大写输出,如果是exit则退出
    BufferedReader br=null;
    try {
        InputStreamReader isr = new InputStreamReader(System.in);
        br = new BufferedReader(isr);
        while(true){
            System.out.println("请输入字符串: ");
            String s = br.readLine();
            if("e".equalsIgnoreCase(s)||"exit".equalsIgnoreCase(s)){
                System.out.println("程序结束");
                break;
            }
            String s1 = s.toUpperCase();
            System.out.println(s1);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if(br!=null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
           

打印流

public static void main(String[] args){
      PrintStream ps=null;
      try {
          FileOutputStream fos = new FileOutputStream(new File("hello.txt"),true);
          ps = new PrintStream(fos, true);
          if(ps!=null){
              System.setOut(ps);
          }
          System.out.println("这是控制台要要输入的数据");
      } catch (FileNotFoundException e) {
          e.printStackTrace();
      }finally {
          if(ps!=null) ps.close();
      }
  }
           

数据流

用于读取或写出基本数据类型的变量或字符串
public static void main(String[] args) throws Exception {
        //从用户读取数据
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a String: ");
        String data = sc.nextLine();
        byte[] buf = data.getBytes();
        //将其写入文件
        DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt"));
        for (byte b:buf) {
            dos.writeChar(b);
        }
        dos.flush();
        //Reading from the above created file using readChar() method
        DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));
        while(true) {
            char ch;
            try {
                ch = dis.readChar();
                System.out.print(ch);
            } catch (EOFException e) {
                System.out.println("");
                System.out.println("End of file reached");
                break;
            } catch (IOException e) {}
        }
    }
           

对象流

用于存储和读取基本数据类型数据或对象的处理流,特殊之处在于把java对象写入数据源中,也能把对象从数据源中还原回来

序列化:用ObjectOutputStream类保存基本类型数据或对象

反序列化:用ObjectIntputStream类读取基本类型数据或对象

注意

1、实现接口:serializable

2、当前类提供一个全局常量:serialVersionUID

3、序列化对象的所有属性也应该都是可序列化的

4、ObjectOutputStream和ObjectIntputStream不能序列化staitc和transient标识的修饰的成员变量

JavaSE——IO流

`

//序列化:将内存中的java对象保存在磁盘中或者通过网络传输出去
ObjectOutputStream oos = null;
try {
    oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
    oos.writeObject(new String("dcdnp"));
    oos.flush();
} catch (IOException e) {
    e.printStackTrace();
}finally {
    if(oos!=null) {
        try {
            oos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
           
ObjectInputStream ois = null;
try {
    ois = new ObjectInputStream(new FileInputStream("object.dat"));
    Object o = ois.readObject();
    String s = (String) o;
    System.out.println(s);
} catch (IOException e) {
    e.printStackTrace();
} catch (ClassNotFoundException e) {
    e.printStackTrace();
}finally {
    if(ois!=null) {
        try {
            ois.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
           
自定义类序列化
public class test{
    public static void main(String[] args){
        //序列化:将内存中的java对象保存在磁盘中或者通过网络传输出去
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
            oos.writeObject(new stu("dcd",20));
            oos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(oos!=null) {
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new FileInputStream("object.dat"));
            Object o = ois.readObject();
            stu s = (stu) o;
            System.out.println(s);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }finally {
            if(ois!=null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

class stu implements Serializable {//标识接口
    public static final long serialVersionUID = 4246546564651321L;//提供一个全局常量
    String name;
    int age;
    stu(){}
    stu(String n, int a){
        name=n;
        age=a;
    }

    @Override
    public String toString() {
        return "student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

           

随机存取文件流

1、直接继承于Object类,实现了两个接口,DataInput和DataOutput

2、既可以作为一个输入流、又可以作为一个输出流

3、会对文件内容进行覆盖,例如:abcd作为输出文件,ef为输入文件,则结果变为efcd

mode参数:

r:以只读的方式打开

rw:打开以便读取和写入

rwd:打开以便读取和写入:同步文件内容的更新

rws:代开以便读取和写入:同步文件内容和元数据的更新

public static void main(String[] args) throws IOException {
    RandomAccessFile raf = new RandomAccessFile("hello.txt", "r");
    RandomAccessFile rw = new RandomAccessFile("Hello1.txt", "rw");
    byte[] cbuf = new byte[1024];
    int len;
    while((len=raf.read(cbuf))!=-1){
        rw.write(cbuf, 0, len);
    }
    raf.close();
    rw.close();
}
           

实现插入操作,是覆盖式的插入

public static void main(String[] args) throws IOException {
    RandomAccessFile raf = new RandomAccessFile("hello.txt", "rw");
    raf.seek(2);
    StringBuilder stringBuilder = new StringBuilder((int) new File("hello.txt").length());
    byte[] cbuf = new byte[20];
    int len;
    while((len=raf.read(cbuf))!=-1){
        stringBuilder.append(new String(cbuf,0,len));
    }
    raf.seek(2);
    raf.write("abc".getBytes(StandardCharsets.UTF_8));
    raf.write(stringBuilder.toString().getBytes(StandardCharsets.UTF_8));
    raf.close();
}
}