Java基础 - IO如此简单

大家好,我是一只学弱狗,记录学习的点点滴滴!

优质文章

优质专栏



分类:

  1. 按数据流的方向不同可以分为输入流输出流
  2. 按处理数据单位可以分为字节流字符流
  3. 按照功能不同可以分为节点流处理流

概念:

节点流:可以从一个特定的数据源(节点)读写数据(如:文件,内存)

在这里插入图片描述

处理流:是“连接”在已存在的流(节点流或处理流)之上,通过对数据的处理为程序提供更为强大的读写功能

在这里插入图片描述

字节流 字符流
输入流 InputStream Reader
输出流 OutputStream Writer

InputStream

概念:继承自InputStream的流都是用于向程序中输入数据,且数据的单位为字节(8 bit),深色为节点流,浅色为处理流

在这里插入图片描述

基本方法
  • int read() throws IOException
    

    读取一个字节并以整数的形式返回(0~255),如果返回-1已到输入流的末尾

  • int read(byte[] buffer) throws IOException
    

    读取一系列字节并存储到一个数组buffer,返回实际读取的字节数,如果读取前已到输入流的末尾返回-1

  • int read(byte[] buffer,int offset,int length) throws IOException
    

    读取length个字节,并存储到一个字节数组buffer,从offset位置开始,返回实际读取的字节数,如果读取前已到输入流的末尾返回-1

  • void close() throws IOException
    

    关闭流释放内存资源


OutputStream

概念:继承自OutputStream的流是用于程序中输出数据,且数据的单位为字节,下图中深色为节点流,浅色为处理流

在这里插入图片描述

基本方法
  • int write(int b) throws IOException
    

    向输出流中写入一个字节数据,该字节数据为参数b的低8位

  • int write(byte[] buffer) throws IOException
    

    将一个字节类型的数组中的数据写入输出流

  • int write(byte[] buffer,int offset,int length) throws IOException
    

    将一个字节类型的数组中的从指定位置offset开始的length个字节写入到输出流

  • void close() throws IOException
    

    关闭流释放内存资源

  • void flush() throws IOException
    

    将输出流中的缓冲的数据全部写出到目的地


Reader

概念:继承自Reader的流是用于程序中输入数据,且数据的单位为字符(16 bit),下图中深色为节点流,浅色为处理流

在这里插入图片描述

基本方法
  • int read() throws IOException
    

    读取一个字符并以整数的形式返回(0~255),如果返回-1已到输入流的末尾

  • int read(char[] buffer) throws IOException
    

    读取一系列字符并存储到一个数组buffer,返回实际读取的字符数,如果读取前已到输入流的末尾返回-1

  • int read(char[] buffer,int offset,int length) throws IOException
    

    读取length个字符,并存储到一个字符数组buffer,从offset位置开始,返回实际读取的字符数,如果读取前已到输入流的末尾返回-1

  • void close() throws IOException
    

    关闭流释放内存资源


Writer

概念:继承自Writer的流是用于程序中输出数据,且数据的单位为字符,下图中深色为节点流,浅色为处理流

在这里插入图片描述

基本方法
  • int write(int b) throws IOException
    

    向输出流中写入一个字符数据,该字节数据为参数b的低16位

  • int write(char[] buffer) throws IOException
    

    将一个字符类型的数组中的数据写入输出流

  • int write(char[] buffer,int offset,int length) throws IOException
    

    将一个字符类型的数组中的从指定位置offset开始的length个字符写入到输出流

  • void write(String string) throws IOException
    

    将一个字符串中的字符写入到输出流

  • void write(String string,int offset,int length) throws IOException
    

    将一个字符串从offset开始的length个字符写入到输出流

  • void close() throws IOException
    

    关闭流释放内存资源

  • void flush() throws IOException
    

    将输出流中的缓冲的数据全部写出到目的地


节点流类型

在这里插入图片描述

FileInputStream
package pers.lele;

import java.io.FileInputStream;
import java.io.IOException;

public class TestFileInputStream {
    
    
    public static void main(String[] args) {
    
    

        FileInputStream fis = null;

        try {
    
    
            fis = new FileInputStream("E:\\IdeaProjects\\JavaIOStream\\src\\pers\\lele\\TestFileInputStream.java");
        } catch (Exception e) {
    
    
            System.out.println("找不到指定文件");
            System.exit(-1);
        }

        int b;
        long num = 0;

        try {
    
    
            while ((b = fis.read()) != -1) {
    
    
                System.out.print((char) b);
                num++;
            }
            fis.close();
            System.out.println("共读取了" + num + "个字节");
        } catch (Exception e) {
    
    
            System.out.println("文件读取错误");
            System.exit(-1);
        }
    }
}

FileOutputStream
package pers.lele;

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

public class TestFileOutputStream {
    
    
    public static void main(String[] args) {
    
    
        FileInputStream fis = null;
        FileOutputStream fos = null;

        int b;

        try {
    
    

            fis = new FileInputStream("E:\\IdeaProjects\\JavaIOStream\\src\\pers\\lele\\TestFileOutputStream.java");
            fos = new FileOutputStream("D:/temp/TestFileOutputStream.java",false);

            while ((b = fis.read())!=-1){
    
    
                fos.write(b);
            }

            fis.close();
            fos.close();
        } catch (FileNotFoundException e) {
    
    
            System.out.println("找不到指定文件");
            System.exit(-1);
        } catch (IOException e) {
    
    
            System.out.println("文件复制异常");
            System.exit(-1);
        }
        System.out.println("文件已经复制");
    }
}


FileReader
package pers.lele;

import java.io.FileReader;
import java.io.FileWriter;

public class TestFileReader {
    
    
    public static void main(String[] args) {
    
    

        FileReader fr = null;

        try {
    
    
            fr = new FileReader("E:\\IdeaProjects\\JavaIOStream\\src\\pers\\lele\\TestFileReader.java");
        } catch (Exception e) {
    
    
            System.out.println("找不到指定文件");
            System.exit(-1);
        }

        int b;
        long num = 0;
        try {
    
    
            while ((b = fr.read()) != -1) {
    
    
                System.out.print((char) b);
                num++;
            }
            fr.close();
            System.out.println("共读取了" + num + "个字节");
        } catch (Exception e) {
    
    
            System.out.println("文件读取错误");
            System.exit(-1);
        }

    }
}

FileWriter
package pers.lele;

import java.io.FileWriter;
import java.io.IOException;

public class TestFileWriter {
    public static void main(String[] args) {
        FileWriter fw = null;

        try {
            fw = new FileWriter("D:/temp/TestFileWriter.java");
        } catch (IOException e) {
            System.out.println("没有发现指定文件");
            System.exit(-1);
        }

        try {
            for (int i = 0; i <= 5000; i++) {
                fw.write(i);
            }
        } catch (IOException e) {
            System.out.println("读写异常");
            System.exit(-1);
        }
        System.out.println("读写成功");
    }
}


处理流类型

在这里插入图片描述

缓冲流:“套接”在相应的节点流之上,对读写的数据提供了缓冲的功能,提高了读写的效率,同时增加了一些新的方法
BufferedReader (Reader in) 						//创建使用默认大小的输入缓冲区的缓冲字符输入流
BufferedReader (Reader in, int size)  			//创建使用指定大小的输入缓冲区的缓冲字符输入流
BufferedWriter (Writer out) 					//创建使用默认大小的输出缓冲区的缓冲字符输出流
BufferedWriter (Writer out, int size) 			//创建使用指定大小的输出缓冲区的缓冲字符输出流
BufferedInputStream (InputStream in) 			//创建一个BufferedInputStream并保存其参数,输入流in供以后使用。 
BufferedInputStream (InputStream in,int size)   //创建具有指定缓冲区大小的BufferedInputStream保存其参数,输入流in供以后使用 
BufferedOutputStream (OutputStream out) 		//创建一个新的缓冲输出流,以将数据写入指定的底层输出流。 
BufferedOutputStream (OutputStream out,int size)//创建一个新的缓冲输出流,以便以指定的缓冲区大小将数据写入指定的底层输出流。

缓冲输入流支持其父类的mark和reset方法

BufferedReader提供了readLine方法用于读取一行数据

BufferedWriter提供了newLine用于写入一个行分隔符

对于输出的缓冲流,写出的数据会先在内存中缓存,使用flush方法会将内存中的数据立即写出

BufferedInputStream
package pers.lele;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class TestBufferedInputStream {
    
    
    public static void main(String[] args) {
    
    
        FileInputStream fis = null;
        BufferedInputStream bis = null;

        try {
    
    
            fis = new FileInputStream("E:\\IdeaProjects\\JavaIOStream\\src\\pers\\lele\\TestBufferedInputStream.java");
            bis = new BufferedInputStream(fis);

            int c = 0;
            System.out.println((char) bis.read());
            System.out.println((char) bis.read());

            bis.mark(100);
            for (int i = 0; i <= 10 && (c = bis.read()) != -1; i++) {
    
    
                System.out.print((char)c);
            }
            System.out.println();
            bis.reset();
            for (int i = 0; i <= 10 && (c = bis.read()) != -1; i++) {
    
    
                System.out.print((char) c);
            }
        } catch (FileNotFoundException e) {
    
    
            System.out.println("文件未发现");
            System.exit(-1);
        } catch (IOException e) {
    
    
            System.out.println("读写异常");
            System.exit(-1);
        }

    }
}
BufferedWriter BufferedRead
package pers.lele;

import java.io.*;

public class TestBufferedWR {
    
    
    public static void main(String[] args) {
    
    
        FileWriter fw = null;
        BufferedWriter bw = null;
        FileReader fr = null;
        BufferedReader br = null;
        try {
    
    
            fw = new FileWriter("D:/temp/TestBufferedWR.java");
            bw = new BufferedWriter(fw);
            fr = new FileReader("D:/temp/TestBufferedWR.java");
            br = new BufferedReader(fr);

            String str = null;
            for (int i = 1; i <= 100; i++) {
    
    
                str = String.valueOf(Math.random());
                bw.write(str);
                bw.newLine();
            }
            bw.flush();

            while ((str = br.readLine()) != null){
    
    
                System.out.println(str);
            }
        } catch (IOException e) {
    
    
            System.out.println("文件未发现");
            System.exit(-1);
        } finally {
    
    
            try {
    
    
                bw.close();
                br.close();
            } catch (IOException e) {
    
    
                e.printStackTrace();
            }
        }
    }
}

转换流:将字节流转化为字符流
//InputStreamReader和OutputStreamWriter是从字节流到字符流的桥梁
OutputStreamWrite
package pers.lele;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class TestTransForm1 {
    
    

    public static void main(String[] args) {
    
    
        try {
    
    
            OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("D:/temp/bat.txt"));
            osw.write("mirocsoftibmsunapplehp");
            System.out.println(osw.getEncoding());
            osw.close();

            //true表示追加
            osw = new OutputStreamWriter(new FileOutputStream("D:/temp/bat.txt",true),"ISO8859_1");
            osw.write("mirocsoftibmsunapplehp");
            System.out.println(osw.getEncoding());
            osw.close();

        } catch (FileNotFoundException e) {
    
    
            System.out.println("未发现指定文件");
            System.exit(-1);
        } catch (IOException e) {
    
    
            System.out.println("读写异常");
            System.exit(-1);
        }
    }

}
InputStreamRead
package pers.lele;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class TestTransForm2 {
    
    
    public static void main(String[] args) {
    
    

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str = null;
        try {
    
    
            str = br.readLine();
            while (str != null) {
    
    
                if ("exit".equalsIgnoreCase(str)) {
    
    
                    break;
                }
                System.out.println(str.toUpperCase());
                str = br.readLine();
            }
            br.close();
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }
}

数据流(DataInputStream和DataOutputStream):提供了可以存储与机器无关的Java原始类型数据(如int,double等)的方法
package pers.lele;

import java.io.*;

public class TestDataStream {
    
    

    public static void main(String[] args) {
    
    
        //实现了将数据写入字节数组的输出流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        DataOutputStream dos = new DataOutputStream(baos);

        try {
    
    
            dos.writeDouble(Math.random());
            dos.writeBoolean(true);
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            //available():返回有效字节数
            System.out.println(bais.available());
            DataInputStream dis = new DataInputStream(bais);
            System.out.println(dis.readDouble());
            System.out.println(dis.readBoolean());
            dos.close();
            dis.close();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }

    }

}

Print流
  • PrintWriter和PrintStream都属于输出流,分贝针对字符和字节
  • PrintWriter和PrintStream提供了重载的print
  • Println方法用于多种数据类型的输出
  • PrintWriter和PrintStream的输出操作不会抛出异常,通过检测错误状态获取错信息
  • PrintWriter和PrintStream有自动flush功能
PrintWriter​(Writer out) 创建一个新的PrintWriter,没有自动线冲洗 
PrintWriter​(Writer out, boolean autoFlush) 创建一个新的PrintWriter 
PrintWriter​(OutputStream out) 从现有的OutputStream创建一个新的PrintWriter,而不需要自动线路刷新
PrintWriter​(OutputStream out, boolean autoFlush) 从现有的OutputStream创建一个新的PrintWriter 
PrintStream​(OutputStream out) 创建一个新的打印流。 
PrintStream​(OutputStream out, boolean autoFlush) 创建一个新的打印流。 
PrintStream
package pers.lele;

import java.io.*;

public class TestPrintStream {
    
    
    public static void main(String[] args) {
    
    
        PrintStream ps = null;

        try {
    
    
            FileOutputStream fos = new FileOutputStream("D:/temp/bat.txt", true);
            ps = new PrintStream(fos);
        } catch (FileNotFoundException e) {
    
    
            e.printStackTrace();
        }

        if (null != ps) {
    
    
            System.setOut(ps);
        }

        int ln = 0;
        for (char c = 0; c <= 600; c++) {
    
    
            System.out.print(c+" ");
            if(ln++ >=100){
    
    
                System.out.println();
                ln = 0;
            }
        }
    }
}

	package pers.lele;

import java.io.*;

public class PrintStream2 {
    
    
    public static void main(String[] args) {
    
    
        String fileName = "D:/temp/bat.txt";
        list(fileName,System.out);
    }
    public static void list(String fileName, PrintStream ps){
    
    
        try {
    
    
            BufferedReader br = new BufferedReader(new FileReader(fileName));

            String s = null;
            while ((s = br.readLine())!=null){
    
    
                ps.println(s);
            }
            br.close();
        } catch (FileNotFoundException e) {
    
    
            e.printStackTrace();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }
}

package pers.lele;

import java.io.*;

/**
 * 通过键盘读数据,将数据写入文件中
 */

public class PrintStream3 {
    
    
    public static void main(String[] args) {
    
    

        try {
    
    
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            PrintWriter pw = new PrintWriter(new FileWriter("D:/temp/bat.txt", true));

            String str = null;
            while((str = br.readLine())!=null){
    
    
                if("exit".equalsIgnoreCase(str)){
    
    
                    break;
                }
                pw.println(str);
                pw.flush();
            }

            br.close();
            pw.close();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }

    }
}

Object流
package pers.lele;

import java.io.*;

public class TestObjectIO {
    
    
    public static void main(String[] args) throws IOException, ClassNotFoundException {
    
    
        T t = new T();
        FileOutputStream fos = new FileOutputStream("D:/temp/bat.txt");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(t);
        oos.flush();
        oos.close();
        System.out.println("-----------华丽丽-----------");
        FileInputStream fis = new FileInputStream("D:/temp/bat.txt");
        ObjectInputStream ois = new ObjectInputStream(fis);
        T object = (T) ois.readObject();
        System.out.println("x: "+object.x);
        System.out.println("y: "+object.y);
        System.out.println("w: "+object.w);
        System.out.println("h: "+object.h);
    }
}

class T implements Serializable
{
    
    
    int x = 5;
    int y = 15;
    double w = 50;
    //transient 透明的
    transient double h = 100;
}

猜你喜欢

转载自blog.csdn.net/qq_44486437/article/details/108377552