Java基础:IO编程

IO编程

1、IO流脑图

2、IO流分类

image-20210903163413192

image-20210903163440828

image-20210903171155474

3、File类操作文件

image-20210903171858267

4、访问文件

字节流:FileInputStream & FileOutputStream

/**
     * FileInputStreamTest
     * @throws IOException
     */
    @Test
    public void test01() throws IOException {
        String path = "F:\\file2.txt";
        FileInputStream fileInputStream = new FileInputStream(path);
        int readLen = 0;
        byte[] buf = new byte[8];
        while ((readLen = fileInputStream.read(buf)) != -1) {
            System.out.println(new String(buf, 0, readLen));
        }
        fileInputStream.close();
    }

    /**
     * FileOutputStreamTest
     * @throws IOException
     */
    @Test
    public void test02() throws IOException {
        String path = "F:\\file2.txt";
        FileOutputStream fileOutputStream = new FileOutputStream(path);
        fileOutputStream.write('h');//追加写入,默认写入末尾
        fileOutputStream.write(11);
        fileOutputStream.write("hello,world".getBytes());
    }

    /**
     * 案例:拷贝文件
     * @throws IOException
     */
    @Test
    public void test03() throws IOException {
        FileInputStream fileInputStream = new FileInputStream("F:\\png1.png");
        FileOutputStream fileOutputStream = new FileOutputStream("F:\\png2.png");

        byte[] buf = new byte[1024];
        int readLine = 0;

        while ((readLine = fileInputStream.read(buf)) != -1) {
            fileOutputStream.write(buf);
        }
        System.out.println("ok~~~");
    }

字符流:FileReader & FileWriter

/**
     * FileReaderTest
     */
    @Test
    public void test04() throws IOException {
        String filePath = "F:\\file2.txt";
        FileReader fileReader = new FileReader(filePath);
        int readLen = 0;
        char[] buf = new char[8];
        while ((readLen = fileReader.read(buf)) != -1) {
            System.out.println(new String(buf, 0, readLen));
        }
    }

    /**
     * FileWriter
     * @throws IOException
     */
//        fileWriter.close();
//        write(int):写入单个字符
//        write(char[]):写入指定数组
//        write(char[],off,len):写入指定数组的指定部分
//        write(string):弓入整个字符串
//        write(string,off,len):写入字符串的指定部分
    @Test
    public void test05() throws IOException {
//        new FileWriter(File/String):覆盖模式,相当于流的指针在首端
//        new FileWriter(File/String,true):追加模式,相当于流的指针在尾端
        FileWriter fileWriter = new FileWriter("F:\\file2.txt", true);
        fileWriter.write(999);
        char[] chars = new char[]{'a', 'b', 'c', 4, 5, 6};
        fileWriter.write(chars);
        fileWriter.write("stringstr");
        fileWriter.flush();

    }

5、缓冲流

image-20210903171257771

字节流:BufferedInputStream & BufferedOutputStream

    /**
     * 案例:拷贝文件:BufferedInputStream
     * @throws IOException
     */
    @Test
    public void test12() throws IOException {
        BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream("F:\\png1.png"));
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("F:\\png2.png"));
        int readdata;
        while ((readdata = bufferedInputStream.read()) != -1) {
            bufferedOutputStream.write(readdata);
        }
        bufferedInputStream.close();
        bufferedOutputStream.close();
    }

    /**
     * 案例:拷贝文件:BufferedInputStream,byte[]
     */
    @Test
    public void test13() throws IOException {
        BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream("F:\\png1.png"));
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("F:\\png2.png"));
        byte[] buf = new byte[1024];
        int readdata;
        while ((readdata = bufferedInputStream.read(buf)) != -1) {
            bufferedOutputStream.write(buf, 0, readdata);
        }
        bufferedInputStream.close();
        bufferedOutputStream.close();
    }

字符流:BufferedReader & BufferedWriter

    /**
     * BufferedReaderTest
     * @throws IOException
     */
    @Test
    public void test08() throws IOException {
        String path = "F:\\file2.txt";
        BufferedReader bufferedReader = new BufferedReader(new FileReader(path));
        String readData;
        while ((readData = bufferedReader.readLine()) != null) {
            System.out.println(readData);
        }
        bufferedReader.close();
    }

    /**
     * BufferedWriterTest
     * @throws IOException
     */
    @Test
    public void test09() throws IOException {
        String path = "F:\\file2.txt";
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(path, true));

        bufferedWriter.write("hello");
        bufferedWriter.newLine();
        bufferedWriter.write("world");
        bufferedWriter.newLine();

        bufferedWriter.close();
    }

    /**
     * 案例:文件拷贝,
     *
     * @throws IOException
     */
    @Test
    public void test10() throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new FileReader("F:\\hello.txt"));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("F:\\helloworld.txt"));
        String readData;
        while ((readData = bufferedReader.readLine()) != null) {
            bufferedWriter.write(readData);
            bufferedWriter.newLine();
        }
        bufferedReader.close();
        bufferedWriter.close();
    }

    /**
     * 案例:文件拷贝,二进制文件(png,pdf,mp4),文件损毁
     * @throws IOException
     */
    @Test
    public void test11() throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new FileReader("F:\\png1.png"));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("F:\\png2.png"));
        String readData;
        while ((readData = bufferedReader.readLine()) != null) {
            bufferedWriter.write(readData);
            bufferedWriter.newLine();
        }
        bufferedReader.close();
        bufferedWriter.close();
    }

6、对象流

对象流只有字节流

image-20210903172702091

image-20210903172653329

字节流:ObjectOutputStream & ObjectInputStream

 /**
     * 序列化:ObjectOutputStream
     * @throws IOException
     */
    @Test
    public void test14() throws IOException {
        //文件后缀名没有意义,
        String path = "F:\\hi.txt";
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path));
//        oos.write(100);//没有类型
        oos.writeInt(100);//int->Integer
        oos.writeBoolean(true);//boolean->Boolean
        oos.writeChar('H');//char->Char
        oos.writeDouble(3.14);//double->Double
        oos.writeUTF("张三&李四");//String
        oos.writeObject(new Dog("王五", 17));//java.io.NotSerializableException

        oos.close();
    }

    /**
     * 反序列化:ObjectInputStream
     *
     * @throws IOException
     */
    @Test
    public void test15() throws IOException, ClassNotFoundException {

        String path = "F:\\hi.txt";
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path));

        //读取(反序列化)顺序 要和 写入(序列化)顺序 保持一致
        //否则异常:java.io.EOFException
        System.out.println(ois.readInt());
        System.out.println(ois.readBoolean());
        System.out.println(ois.readChar());
        System.out.println(ois.readDouble());
        System.out.println(ois.readUTF());
        Object o = ois.readObject();
        System.out.println((Dog) o);

        //注意细节:
        //1.如果我们希望调用Dog里面的方法,需要向下转型
        //2.需要我们将Dog类的定义,写在可以引用的地方

        //3.如果在序列化之后,Dog类里面的内容进行了修改
        //  那么,必须在 反序列化之前重新 序列化
        System.out.println(((Dog) o).getAge());
        System.out.println(((Dog) o).getName());
    }

7、转换流

image-20210903171355809

字符流:InputStreamReader & OutputStreamWriter

/**
     * 问题引入:中文编码,乱码
     * @throws IOException
     */
    @Test
    public void test17() throws IOException {
        //读取文件,默认 utf-8
        String path = "F:\\Hello.txt";
        //如果读取的不是utf-8编码的文件,则会乱码
        BufferedReader bufferedReader = new BufferedReader(new FileReader(path));
        System.out.println(bufferedReader.readLine());//HellJavaWorld�������
        bufferedReader.close();
    }

    /**
     * InputStreamReader 解决中文乱码
     * @throws IOException
     */
    @Test
    public void test18() throws IOException {
        //文件是以 ANSI 编码
        String path = "F:\\Hello.txt";
        //希望以 gbk 编码读取
        InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(path), "gbk");
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String s = bufferedReader.readLine();
        System.out.println(s);//HellJavaWorld你好世界
        bufferedReader.close();
    }

    /**
     * OutputStreamWriter:以指定的编码写入文件
     * @throws IOException
     */
    @Test
    public void test19() throws IOException {
        String path = "F:\\hello.txt";
        String charSet = "GBK";

        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(path), charSet);

        osw.write("hello");
        osw.write("张三");

        osw.close();
    }

8、打印流

image-20210903171455625

字节流:PrintStream

/**
     * PrintStream
     * @throws IOException
     */
    @Test
    public void test20() throws IOException {

        PrintStream out = System.out;
        out.println("hello,world"); //打印到控制台
        /*  println = print + newline
            print 底层 也就是 write
            public void print(String s) {
            if (s == null) {
                s = "null";
             }
             write(s);
             }
         */
        out.write("hello,张三".getBytes());
        out.close();

        //可以修改打印流输出的位置
        //修改输出到 文件:
        System.setOut(new PrintStream("F:\\f1.txt"));
        //会打印到文件中,不再是控制台
        System.out.println("hello,李四");
        /* 源码:
         public static void setOut(PrintStream out) {
            checkIO();
            setOut0(out); //native方法
         }

         private static native void setOut0(PrintStream out);
         */

    }

字符流:PrintWriter

    /**
     * PrintWriter 控制台输出
     * @throws IOException
     */
    @Test
    public void test21() throws IOException {
        PrintWriter printWriter = new PrintWriter(System.out);
        printWriter.print("hello,田七");
        printWriter.close();
    }

    /**
     * printWriter,输出到文件
     * @throws IOException
     */
    @Test
    public void test22() throws IOException {
        PrintWriter printWriter = new PrintWriter(new FileWriter("F:\\f2.txt"));
        printWriter.print("hello,田七");
        printWriter.close();
    }

9、标准输入输出流

image-20210903171435773

    /**
     * 标准输入,输出流
     * System.in & System.out
     */
    @Test
    public void test16() {

        //System.in源码:public final static InputStream in = null;
        //编译类型:InputStream
        //运行类型:BufferedInputStream
        System.out.println(System.in.getClass());//class java.io.BufferedInputStream

        //System.out源码:public final static PrintStream out = null;
        //编译类型:PrintStream
        //运行类型:PrintStream
        System.out.println(System.out.getClass());//class java.io.PrintStream

    }

10、Properties类

/**
     * 使用 Properties 创建文件
     * @throws IOException
     */
    @Test
    public void test23() throws IOException {

        Properties properties = new Properties();
        //添加数据
        properties.setProperty("id", "127.0.0.1");
        properties.setProperty("user", "zhangsan张三");//中文将会以 unicode码 的方式保存在文件中
        properties.setProperty("pwd", "66666666");
        //保存
        //第二个参数,用于设置 配置文件 的注解,
        //如果 填写null,会自动为你添加当前时间 例:#Tue Aug 31 19:51:16 CST 2021
        //如果 不是非null,则会在 文件首行添加  # 你填写的内容(中文为unicode码) + [换行] + 当前时间
        properties.store(new FileOutputStream("F:\\mysql.properties"), "这是一个注释");

        System.out.println("保存成功~~");

    }

    /**
     * 读取 properties 文件数据
     * @throws IOException
     */
    @Test
    public void test24() throws IOException {
        Properties properties = new Properties();
        //加载文件
        properties.load(new FileReader("F:\\mysql.properties"));
        //获取整个数据列表,并输出在 控制台上
        //properties底层是 hashtable,所以 添加的顺序 != 存放的顺序
        //class Properties extends Hashtable<Object,Object>
        properties.list(System.out);

        String user = properties.getProperty("user");
        String pwd = properties.getProperty("pwd");
        System.out.println(user);
        System.out.println(pwd);
    }

    /**
     * 修改 properties 值
     *
     * @throws IOException
     */
    @Test
    public void test25() throws IOException {
        Properties properties = new Properties();
        //添加数据
        properties.setProperty("id", "127.0.0.1");
        properties.setProperty("user", "zhangsan张三");//中文将会以 unicode码 的方式保存在文件中
        properties.setProperty("pwd", "66666666");

        //获取修改前的数据
        properties.list(System.out);

        //修改数据
        //如果 key存在,再次添加 就是修改
        properties.setProperty("user", "lisi李四");

        //获取修改后的数据
        properties.list(System.out);
    }

11、随机文件存取流

image-20210903172519681

image-20210903172501588

RandomAccessFile

/**
 * @Author: 
 * @Date: 2021/9/2 10:21
 */
public class demo03 {

    /**
     * RandomAccessFile 复制文件
     */
       @Test
    public void test01() throws IOException {

        RandomAccessFile raf1 = null;
        RandomAccessFile raf2 = null;
        raf1 = new RandomAccessFile(new File("png1.png"), "r");
        raf2 = new RandomAccessFile(new File("png2.png"), "rw");

        byte[] buff = new byte[1024];
        int len;
        while ((len = raf1.read(buff)) != -1) {
            raf2.write(buff, 0, len);
        }
        raf1.close();
        raf2.close();

    }

    /**
     * RandomAccessFile
     * 没有文件时,自动创建
     * 有文件时,从头覆盖,覆盖几个算几个
     * @throws IOException
     */
    @Test
    public void test02() throws IOException {
        RandomAccessFile raf=new RandomAccessFile(new File("hello.txt"),"rw");
        raf.write("hihihihi".getBytes());
        //原文件内容:hello,everyone大家好
        //修改后文件:hihihihieryone大家好
        raf.close();
    }


    /**
     * RandomAccessFile 追加写入
     * @throws IOException
     */
    @Test
    public void test03() throws IOException {
        File file = new File("hello.txt");
        RandomAccessFile raf=new RandomAccessFile(file,"rw");
        //seek,定位到文件最后面
        raf.seek(file.length());
        raf.write("hihihihi".getBytes());
        //原文件内容:hello,everyone大家好
        //修改后文件:hello,everyone大家好 <换行> hihihihi
        raf.close();
    }


    /**
     * RandomAccessFile seek定位实现插入
     * @throws IOException
     */
    @Test
    public void test04() throws IOException{

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

        raf.seek(6);

        //保存指针5后面的所有数据
        StringBuilder builder=new StringBuilder((int) file.length());
        byte[] buff=new byte[1024];
        int len;
        while ((len=raf.read(buff))!=-1){
           builder.append(new String(buff,0,len));
        }

        //调回指针
        raf.seek(6);
        //写入 要插入的数据
        raf.write("hihiihi".getBytes());

        //写回
        raf.write(builder.toString().getBytes());

        raf.close();

        //原文件内容:hello,everyone大家好
        //修改后文件:hello,hihiihieveryone大家好
    }
}

12、第三方JAR包

FileUtils

推荐阅读:https://www.cnblogs.com/deityjian/p/11106981.html

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>
1.写 文件/文件夹
/* 写文件 
 * 1.这里只列出3种方式全参数形式,api提供部分参数的方法重载 
 * 2.最后一个布尔参数都是是否是追加模式 
 * 3.如果目标文件不存在,FileUtils会自动创建 
 * */  
//static void:write(File file, CharSequence data, String encoding, boolean append)   
FileUtils.write(new File("D:/a/b/cxyapi.txt"), "程序换api","UTF-8",true);  
  
//static void:writeLines(File file, Collection<?> lines, boolean append)   
List<String> lines=new ArrayList<String>();  
lines.add("欢迎访问:");lines.add("www.cxyapi.com");  
FileUtils.writeLines(new File("D:/a/b/cxyapi.txt"),lines,true);  
  
//static void:writeStringToFile(File file, String data, String encoding, boolean append)   
FileUtils.writeStringToFile(new File("D:/a/b/cxyapi.txt"), "作者:cxy", "UTF-8",true);  
 

2.读 文件/文件夹
//读文件  
//static String:readFileToString(File file, String encoding)   
System.out.println(FileUtils.readFileToString(new File("D:/a/b/cxyapi.txt"), "UTF-8"));  
  
//static List<String>:readLines(File file, String encoding)   
System.out.println(FileUtils.readLines(new File("D:/a/b/cxyapi.txt"), "UTF-8")); //返回一个list  
 

3.删除 文件/文件夹
//删除目录  
//static void:deleteDirectory(File directory)   
FileUtils.deleteDirectory(new File("D:/not/cxyapi"));  
  
//static boolean:deleteQuietly(File file)   
FileUtils.deleteQuietly(new File("D:/not/cxyapi")); //文件夹不是空任然可以被删除,永远不会抛出异常  
 

4.移动 文件/文件夹
//移动文件 或 文件夹  
//static void:moveDirectory(File srcDir, File destDir)   
FileUtils.moveDirectory(new File("D:/cxyapi1"), new File("D:/cxyapi2")); //注意这里 第二个参数文件不存在会引发异常  
//static void:moveDirectoryToDirectory(File src, File destDir, boolean createDestDir)   
FileUtils.moveDirectoryToDirectory(new File("D:/cxyapi2"), new File("D:/cxyapi3"), true);  
/* 上面两个方法的不同是: 
 * moveDirectory:D:/cxyapi2里的内容是D:/cxyapi1的内容。 
 * moveDirectoryToDirectory:D:/cxyapi2文件夹移动到到D:/cxyapi3里 
 *  
 * 下面的3个都比较简单没提供示例,只提供了api 
 * 其中moveToDirectory和其他的区别是 它能自动识别操作文件还是文件夹 
 */  
//static void:moveFileToDirectory(srcFile, destDir, createDestDir)  
//static void:moveFile(File srcFile, File destFile)   
//static void:moveToDirectory(File src, File destDir, boolean createDestDir)  
 

5.copy
//结果是cxyapi和cxyapi1在同一目录  
FileUtils.copyDirectory(new File("D:/cxyapi"), new File("D:/cxyapi1"));   
//结果是将cxyapi拷贝到cxyapi2下  
FileUtils.copyDirectoryToDirectory(new File("D:/cxyapi"), new File("D:/cxyapi2"));  
  
//拷贝文件  
FileUtils.copyFile(new File("d:/cxyapi.xml"), new File("d:/cxyapi.xml.bak"));  
//拷贝文件到目录中  
FileUtils.copyFileToDirectory(new File("d:/cxyapi.xml"), new File("d:/cxyapi"));  
//拷贝url到文件  
FileUtils.copyURLToFile(new URL("http://www.cxyapi.com/rss/cxyapi.xml"), new File("d:/cxyapi.xml"));  
 

6.其他
//判断是否包含文件或者文件夹  
boolean b=FileUtils.directoryContains(new File("D:/cxyapi"), new File("D:/cxyapi/cxyapi.txt"));  
System.out.println(b);  
  
//获得临时目录 和 用户目录  
System.out.println(FileUtils.getTempDirectoryPath());  
System.out.println(FileUtils.getUserDirectoryPath());  
  
//打开流,如果不存在创建文件及其目录结构  
//第二个参数表示 文件流是否是追加方式  
FileOutputStream fos=FileUtils.openOutputStream(new File("D:/cxyapi/cxyapi.txt"),true);  
fos.write(new String("欢迎访问:www.cxyapi.com\r\n").getBytes());  
fos.close();  
  
//文件 或 文件夹大小  
System.out.println(FileUtils.sizeOf(new File("D:/cxyapi")));  
System.out.println(FileUtils.sizeOfDirectory(new File("D:/cxyapi")));

13、数据流

image-20210903171544593

    /**
     * DataOutputStream
     * @throws IOException
     */
    @Test
    public void test06() throws IOException{
        DataOutputStream dos=new DataOutputStream(new FileOutputStream("data.txt"));
        dos.writeUTF("大家好");
        dos.flush();
        dos.writeInt(33);
        dos.flush();
        dos.writeBoolean(false);
        dos.flush();
    }


    /**
     * DataInputStream
     * @throws IOException
     */
    @Test
    public void test07() throws IOException{
        DataInputStream dis=new DataInputStream(new FileInputStream("data.txt"));
        System.out.println(dis.readUTF());
        System.out.println(dis.readInt());
        System.out.println(dis.readBoolean());
    }

14、访问数组

字节流:ByteArrayInputStream & ByteArrayInputStream

使用字节流,从字节数组中读取数据,以及向字节数组中写数据。

java.io.ByteArrayInputStream 负责从字节数组中读取数据

java.io.ByteArrayOutputStream 负责把数据写入到字节数组中

    @Test
    public void test01() throws IOException {

        byte[] arr="hello,everyone".getBytes();
        //1.创建流
        InputStream in = new ByteArrayInputStream(arr);
        OutputStream out = new ByteArrayInputStream();
        //2.使用流
        int len=0;
        byte[] buff=new byte[1024];
        while ((len= in.read(buff))!=-1){
            System.out.println(new String(buff,0,len));
            //将数据写入out对象中的属性里面
            out.write(buff,0,len);
            out.flush();
        }

        //ByteArrayOutputStream中的toByteArray()方法,可以将out对象中的数据返回
        byte[] toByteArray = ((ByteArrayOutputStream) out).toByteArray();
        System.out.println(Arrays.toString(toByteArray));
        
    }

字符流:CharArrayReader & CharArrayWriter

使用字符流,从字符数组中读取数据,以及向字符数组中写数据。

java.io.CharArrayReader 负责从字符数组中读取数据

java.io.CharArrayWriter 负责把数据写入到字符数组中

    @Test
    public void test02() throws IOException {

        char[] chars = "大家好,我是zhangsan".toCharArray();

        //1.创建流
        Reader reader = new CharArrayReader(chars);
        Writer writer = new CharArrayWriter();
        //2.使用流
        int len=0;
        char[] buff=new char[10];
        while ((len= reader.read(buff))!=-1){
            System.out.println(new String(buff,0,len));
            //将数据写入out对象中的属性里面
            writer.write(buff,0,len);
            writer.flush();
        }

        //CharArrayWriter中的toByteArray()方法,可以将out对象中的数据返回
        char[] array = ((CharArrayWriter) writer).toCharArray();
        System.out.println(Arrays.toString(array));//[大, 家, 好, ,, 我, 是, z, h, a, n, g, s, a, n]

    }

15、访问管道

字节流:PipedInputStream & PipedOutputStream

使用字节流,可以从管道中读取数据,以及向管道中写数据。

java.io.PipedInputStream 负责从管道中读取数据

java.io.PipedOutputStream 负责将数据写入到管道中

注意,一般可以在一个线程中,使用管道输出流,将数据写入到管道中,在另一个线程中,读取管道中 的数据。

image-20210906170505273


   /**
     * 访问管道:字节流 PipedInputStream,PipedOutputStream
     * @throws IOException
     */
    @Test
    public void test03() throws IOException, InterruptedException {
        PipedInputStream in = new PipedInputStream();
        PipedOutputStream out = new PipedOutputStream();

        //管道对接
        in.connect(out);

        Thread t1=new Thread(new Runnable() {
            @Override
            public void run() {
                byte[] arr="hello,world,zhangsan".getBytes();
                try {
                    for (int i = 0; i <arr.length ; i++) {
                        out.write(arr[i]);
                        out.flush();
                        Thread.sleep(10);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        },"写线程");

        Thread t2=new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    int data=0;
                    while ((data=in.read())!=-1){
                        System.out.println(data);//h101
                        System.out.write(data);//
                        System.out.flush();
                    }
                    System.out.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        },"读线程");

        t1.start();
        t2.start();

        t1.join();
        t2.join();

    }
}

字符流:PipedReader & PipedWriter

使用字符流,可以从管道中读取数据,以及向管道中写数据。

java.io.PipedReader 负责从管道中读取数据

java.io.PipedWriter 负责将数据写入到管道中

注意,一般可以在一个线程中,使用管道输出流,将数据写入到管道中,在另一个线程中,读取管道中 的数据。

image-20210906171911789

和之前的管道字节流的操作类似,只是把字节改成了字符进行操作

/**
     * 访问管道:字符流 PipedReader,PipedWriter
     * @throws IOException
     */
    @Test
    public void test04() throws IOException, InterruptedException {

        PipedReader in = new PipedReader();
        PipedWriter out = new PipedWriter();

        //管道对接
        in.connect(out);

        Thread t1=new Thread(new Runnable() {
            @Override
            public void run() {
                char[] arr = "hello,world,zhangsan".toCharArray();
                try {
                    for (int i = 0; i <arr.length ; i++) {
                        out.write(arr[i]);
                        out.flush();
                        Thread.sleep(10);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        },"写线程");

        Thread t2=new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    int data=0;
                    while ((data=in.read())!=-1){
//                        System.out.println(data);//h101
                        System.out.write(data);//
                        System.out.flush();
                    }
                    System.out.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        },"读线程");

        t1.start();
        t2.start();

        t1.join();
        t2.join();

    }

16、访问字符串

字符流:StringReader、StringWriter

只有字符流

    @Test
    public void test05() throws IOException{

        String str="hello大家好,a吗aa,b好bb,大家";
        StringReader stringReader=new StringReader(str);
        StringWriter stringWriter=new StringWriter();
        int len=0;
        char[] chars=new char[6];
       while ((len=stringReader.read(chars))!=-1){
           System.out.println(new String(chars,0,len));
           stringWriter.write(chars);
       }

        StringBuffer buffer = stringWriter.getBuffer();
        System.out.println(buffer);
        
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值