JAVA----IO流

JAVA----IO流

package java0;

import org.junit.Test;

import java.io.*;

/**
 *
 * 一、流的分类
 *  1.按 操作数据单位 分类:字节流、字符流
 *  2.按 数据的流向 分类:输入流、输出流
 *  3.按 流的角色 分类:节点流、处理流
 *
 *  二、流的体系结构
 *
 *  抽象基类            节点流(文件流)                      缓冲流(处理流的一种)
*   InputStream         FileInputStream                     BufferedInputStream
 *  OutputStream        FileOutputStream                    BufferedOutputStream
 *  Reader              FileReader                          BufferedReader
*   Writer              FileWriter                          BufferedWriter
 *
 *
 *   在main中,相对路径是相对于当前工程
 *   在@Test测试方法中,相对路径是相对于当前的Module
 * @create 2022-04-11 18:31
 */
public class FileReaderWriterTest {
    /*
        将hello.txt文件内容读入到程序中,并输出到控制台

        说明:
        1.read()的理解:返回读入的一个字符。如果达到文件末尾,返回-1.
        2.异常的处理:为了保证流资源一定可以执行关闭操作。需要使用try-catch-finally处理
        3.读入的文件一定要存在,否则就会报FileNotFoundException.
     */

    @Test
    public void testFileReader() {
        FileReader fr= null;
        try {
            //1.实例化File类的对象,指明要操作的文件。
            File file=new File("hello.txt");
            //2.提供具体的流
            fr = new FileReader(file);

            //3.数据的读入
//        int data=fr.read();
//        while(data!=-1){
//            System.out.print((char)data);
//            data=fr.read();
//        }

            int data;
            while((data=fr.read())!=-1){
                System.out.print((char)data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            //4.流的关闭操作
            if(fr!=null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //对read()操作升级,使用read的重载方法
    @Test
    public void testFileReader1(){
        FileReader fr= null;
        try {
            //1.File类的实例化
            File file=new File("hello.txt");
            //2.FileReader流的实例化
            fr = new FileReader(file);
            //3.读入的操作
            //read(char[] cbuf):返回每次读入cbuf数组中的字符的个数。如果到达文件末尾,返回-1.
            char[] cbuf=new char[5];
            int len;
            while((len=fr.read(cbuf))!=-1){
//                for(int i=0;i<len;i++){
//                    System.out.print(cbuf[i]);
//                }
                String str=new String(cbuf,0,len);
                System.out.print(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            //4.关闭资源
            if(fr!=null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }


    /*
        从内存中写出数据到硬盘的文件里

        说明:
        1.输出操作,对应的File可以不存在。
        2.
            File对应的硬盘中的文件如果不存在,在输出的过程中,会自动创建此文件。
            File对应的硬盘中的文件如果存在:
                如果流使用的构造器是:FileWriter(file,false) / FileWriter(file) :  会覆盖原有文件
                如果流使用的构造器是:FileWriter(file,true):不会对原有文件覆盖,而是在原有文件基础上追加内容。


     */
    @Test
    public void testFileWriter(){
        FileWriter fw= null;
        try {
            //1.提供File类的对象,指明写出到的文件
            File file=new File("hello1.txt");
            //2.提供FileWriter的对象,用于数据的写出
            fw = new FileWriter(file,false);
            //3.写出的操作
            fw.write("I have a dream!\n");
            fw.write("you need to have a dream!");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.流资源的关闭

            if(fw!=null){
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Test
    public void testFileReaderFileWriter(){
        FileReader fr= null;
        FileWriter fw= null;
        try {
            //1.创建File类的对象
            File srcFile=new File("hello.txt");
            File destFile=new File("hello2.txt");

            //2.创建输入流和输出流的对象

            fr = new FileReader(srcFile);
            fw = new FileWriter(destFile);

            //3.数据的读入和写出操作
            char[] cbuf=new char[5];
            int len;
            while((len=fr.read(cbuf))!=-1){
                fw.write(cbuf,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.关闭资源
            if(fr!=null){
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fw!=null){
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }



}

package java0;

import org.junit.Test;

import java.io.*;

/**
 *
 *结论:
 *  1.对于文本文件(.txt  .java  .c  .cpp),使用字符流处理
 *  2.对于非文本文件(.jpg  .mp3  .mp4  .avi  .doc  .ppt),使用字节流处理
 * @create 2022-04-11 20:47
 */
public class FileInputOutputStream {

    @Test
    public void testFileInputStream(){
        FileInputStream fis= null;
        try {
            //1.创建File类
            File file=new File("hello.txt");
            //2.造流
            fis = new FileInputStream(file);

            //3.读数据
            byte[] buffer=new byte[5];
            int len;
            while ((len=fis.read(buffer))!=-1){
                String str=new String(buffer,0,len);
                System.out.print(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.关闭资源
            if(fis!=null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }


    /*
        实现都图片的复制操作
     */
    @Test
    public void testFileInputOutputStream(){
        FileInputStream fis= null;
        FileOutputStream fos= null;
        try {
            //创建File类
            File srcFile=new File("3.png");
            File destFile=new File("2222.png");
            //创建节点流
            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(destFile);

            //复制的过程
            byte[] buffer=new byte[5];
            int len;
            while((len=fis.read(buffer))!=-1){
                fos.write(buffer,0,len);

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fis!=null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }

    //指定路径下文件的复制
    public void copyFile(String srcPath,String destPath){
        FileInputStream fis= null;
        FileOutputStream fos= null;
        try {
            //创建File类
            File srcFile=new File(srcPath);
            File destFile=new File(destPath);

            //创建流
            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(destFile);

            //复制的过程
            byte[] buffer=new byte[1024];
            int len;
            while ((len=fis.read(buffer))!=-1){
                fos.write(buffer,0,len);

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            if(fis!=null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }


    @Test
    public void testCopyFile(){
        String srcPath="D:\\java\\workspace_idea\\lwb\\day09\\3.png";
        String destPath="C:\\Users\\86156\\Desktop\\lllwb.png";

        copyFile(srcPath,destPath);

    }
}

package java0;

import org.junit.Test;

import java.io.*;

/**
 *
 * 处理流之一:缓冲流
 *  1.缓冲流
 *      BufferedInputStream
 *      BufferedOutputStream
 *      BufferedReader
 *      BufferedWriter
 *
 *  2.作用:提供流的读取,加快写入速度。
 *      提高读写速度的原因:内部提供了一个缓冲区
 *
 *  3.处理流:就是“套接”在已有的流的基础上。
 * @create 2022-04-12 11:39
 */
public class BufferedTest {

    /*
        实现非文本文件的复制

     */

    @Test
    public void BufferedStreamTest(){
        BufferedInputStream bis= null;
        BufferedOutputStream bos= null;
        try {
            //1.造文件
            File srcFile=new File("3.png");
            File destFile=new File("4.png");

            //2.造流
            //2.1造节点流
            FileInputStream fis=new FileInputStream(srcFile);
            FileOutputStream fos=new FileOutputStream(destFile);
            //2.2造缓冲流
            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);

            //3.复制

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

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.关闭资源
            //要先关闭外层的流,再关闭内层的流
            if(bos!=null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(bis!=null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
//        fos.close();
//        fis.close();
            //说明:关闭外层流的同时,也会关闭内层流
        }


    }

    //实现文件复制的方法

    public void copyFileWithBuffered(String srcPath,String destPath){
        BufferedInputStream bis= null;
        BufferedOutputStream bos= null;
        try {
            //1.造文件
            File srcFile=new File(srcPath);
            File destFile=new File(destPath);

            //2.造流
            //2.1造节点流
            FileInputStream fis=new FileInputStream(srcFile);
            FileOutputStream fos=new FileOutputStream(destFile);

            //2.2造缓冲流
            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);

            //3.复制
            byte[] buffer=new byte[1024];
            int len;
            while ((len=bis.read(buffer))!=-1){
                bos.write(buffer,0,len);

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.资源关闭
            if(bos!=null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(bis!=null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    @Test
    public void testCopyFileWithBuffered(){
        long start = System.currentTimeMillis();
        String srcPath="4.png";
        String destPath="5.png";
        copyFileWithBuffered(srcPath,destPath);

        long end = System.currentTimeMillis();

        System.out.println(end-start);

    }


    /*
        使用BufferedWriter和BufferedReader实现文本文件的复制


     */
    @Test
    public void testBufferedWriterReader(){
        BufferedReader br= null;
        BufferedWriter bw= null;
        try {
            //创建文件和相应的流
            br = new BufferedReader(new FileReader(new File("hello.txt")));
            bw = new BufferedWriter(new FileWriter(new File("hello1122.txt")));

            //读写操作

//            char[] cbuf=new char[1024];
//            int len;
//            while ((len=br.read(cbuf))!=-1){
//                bw.write(cbuf,0,len);
//            }

            String data;
            while((data=br.readLine())!=null){
                bw.write(data);
                bw.newLine();
            }



        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(bw!=null){
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }



    }
}

package exer;

import org.junit.Test;

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

/**
 *
 *
 *
 * @create 2022-04-12 12:57
 */
public class PicTest {

    //图片的加密
    @Test
    public void test1(){
        FileInputStream fis= null;
        FileOutputStream fos= null;
        try {
            fis = new FileInputStream("5.png");
            fos = new FileOutputStream("5secret.png");

            byte[] buffer=new byte[1024];
            int len;
            while ((len=fis.read(buffer))!=-1){
                for(int i=0;i<len;i++){
                    buffer[i]= (byte) (buffer[i]^5);
                }
                fos.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fis!=null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }

    //图片的解谜
    @Test
    public void test2(){
        FileInputStream fis= null;
        FileOutputStream fos= null;
        try {
            fis = new FileInputStream("5secret.png");
            fos = new FileOutputStream("5work.png");

            byte[] buffer=new byte[1024];
            int len;
            while ((len=fis.read(buffer))!=-1){
                for(int i=0;i<len;i++){
                    buffer[i]= (byte) (buffer[i]^5);
                }
                fos.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fis!=null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

package java0;

import org.junit.Test;

import java.io.*;

/**
 *
 *转换流(处理流的一种)
 * 1.转换流:属于字符流
 *  InputStreamReader:将一个字节的输入流转换为字符的输入流
 *  OutputStreamWriter:将一个字符的输出流转换为字节的输出流
 *
 *
 *  2.作用:提供字节流与字符流之间的转换
 *
 *  3.解码:字节、字节数组--》字符数组、字符串
 *      编码:字符数组、字符串---》字节、字节数组
 *
 *
 *  4.字符集
 *
 *  ASCII:美国标准信息交换码。用一个字节的7位可以表示。
 *  ISO8859-1:拉丁码表。欧洲码表。用一个字节的8位表示
 *  GB2312:中国的中文编码表。最多两个字节编码所有字符。
 *  GBK:中国的中文编码表升级,融合了更多的中文文字符号。最多两个字节编码。
 *  Unicode:国际标准码,融合了目前人类使用的所有字符。所有的文字都用两个字节表示。
 *  UTF-8:变长的编码方式,可用1-4个字节来表示一个字符。
 *
 * @create 2022-04-12 15:42
 */
public class InputStreamReaderTest {
    @Test
    public void test1(){
        InputStreamReader isr= null;
        try {
            FileInputStream fis=new FileInputStream("hello.txt");
//        InputStreamReader isr=new InputStreamReader(fis);//使用系统默认的字符集
            //参数2指明了字符集,具体使用哪个字符集,取决于文件保存时使用的字符集。
            isr = new InputStreamReader(fis,"UTF-8");
            char[] cbuf=new char[20];
            int len;
            while ((len=isr.read(cbuf))!=-1){
                String str=new String(cbuf,0,len);
                System.out.println(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(isr!=null) {
                try {
                    isr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    @Test
    public void test2(){
        InputStreamReader isr= null;
        OutputStreamWriter osw= null;
        try {
            //造文件、造流
            File file1=new File("hello.txt");
            File file2=new File("hello_GBK.txt");

            FileInputStream fis=new FileInputStream(file1);
            FileOutputStream fos=new FileOutputStream(file2);

            isr = new InputStreamReader(fis,"UTF-8");
            osw = new OutputStreamWriter(fos,"gbk");

            char[] cbuf=new char[20];
            int len;
            while((len=isr.read(cbuf))!=-1){
                osw.write(cbuf,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(isr!=null){
                try {
                    isr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(osw!=null){
                try {
                    osw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }s
            }
        }

    }
}

package java0;

import org.junit.Test;

import java.io.*;

/**
 *1.标准的输入输出流
 * 2.打印流
 * 3.数据流
 *
 * @create 2022-04-12 20:14
 */
public class OtherStream {
    /*
        1.标准的输入、输出流
        1.1
            System.in:标准的输入流,默认从键盘输入
            System.out:标准的输出流,默认从控制台输出。
        1.2
            System类的setIn(InputStream is)/setOut(PrintStream ps)可以重新指定输入和输出的流。

     */

    public static void main(String[] args){
        BufferedReader br= null;
        try {
            InputStreamReader isr=new InputStreamReader(System.in);
            br = new BufferedReader(isr);
            while (true){
                String data=br.readLine();
                if("e".equalsIgnoreCase(data) || "exit".equalsIgnoreCase(data)){
                    System.out.println("程序结束");
                    break;
                }

                String upperCase=data.toUpperCase();
                System.out.println(upperCase);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /*
        打印流:PrintStream 和PrintWriter

     */

    @Test
    public void test2(){
        PrintStream ps= null;
        try {
            FileOutputStream fos=new FileOutputStream(new File("hello.txt"));
            //创建打印输出流,设置为自动刷新模式(写入换行符或字节'\n'时都会刷新输出缓冲区)
            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();
            }
        }

    }

    /*
        3.数据流
            3.1 DataInputStream和DataOutputStream

            3.2 作用:用于读取或写出基本数据类型的变量或字符串

     */


    @Test
    public void test3() throws IOException {
        DataOutputStream dos=new DataOutputStream(new FileOutputStream("hello7.txt"));
        dos.writeUTF("lalala");
        dos.flush();
        dos.writeInt(1122);
        dos.flush();
        dos.writeBoolean(true);
        dos.flush();
        dos.close();
    }

    @Test
    public void test4() throws IOException {
        DataInputStream dis=new DataInputStream(new FileInputStream("hello7.txt"));

        String name=dis.readUTF();
        int age=dis.readInt();
        boolean isMale=dis.readBoolean();
        System.out.println(name+","+age+","+isMale);
    }




}

package java0;

import org.junit.Test;

import java.io.*;

/**
 *
    对象流的使用
    1.ObjectOutputStream和ObjectInputStream
    2.作用:用于存储或读取基本数据类型数据或对象的处理流。
    3.序列化机制:
        对象序列化机制允许把内存中的Java对象转换成平台无关的二进制流,从而允许把这种
    二进制流持久地保存在磁盘上,或通过网络将这种二进制流传输到另一个网络节点。
    当其他程序获取了这种二进制流,就可以恢复成原来的java对象。
 *
 *  补充:ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量。
 * @create 2022-04-13 17:27
 */
public class ObjectOutputInputStream {

    /*
        序列化过程:将内存中的java对象保存到磁盘中或通过网络传输出去
        使用ObjectOutputStream实现。


     */
    @Test
    public void testObjectOutputStream(){
        ObjectOutputStream oos= null;
        try {
            oos = new ObjectOutputStream(new FileOutputStream("Object.dat"));
            oos.writeObject(new String("撒士大夫士大夫"));
            oos.flush();

            oos.writeObject(new Person("张三",23));
            oos.flush();

            oos.writeObject(new Person("张地工",21,1000,new Account(1111)));
            oos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            if(oos!=null){
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /*
        反序列化:将磁盘文件中的对象还原为内存中的一个java对象

     */

    @Test
    public void testObjectInputStream()  {
        ObjectInputStream ois= null;
        try {
            ois = new ObjectInputStream(new FileInputStream("Object.dat"));
            Object obj=ois.readObject();
            String str=(String) obj;

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

            System.out.println(str);
            System.out.println(p);
            System.out.println(p1);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {

            if(ois!=null){
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }




    }
}

package java0;

import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 *RandomAccessFile的使用
 * 1.RandomAccessFile直接继承于java.lang.Object类,实现了DataInput和DatOutput接口
 * 2.RandomAccessFile既可以作为一个输入流,又可以作为一个输出流。
 * 3.如果RandomAccessFile作为输出流时,写出到的文件如果不存在,则在执行过程中自动创建,
 *      如果写出到的文件存在,则会对原有文件内容进行覆盖(默认情况下,从头覆盖)
 *  4.可以通过相关的操作,实现RandomAccessFile插入数据的效果
 *
 *
 *
 * @create 2022-04-13 18:55
 */
public class RandomAccessFileTest {


    @Test
    public void test1() {
        RandomAccessFile raf1= null;
        RandomAccessFile raf2= null;
        try {
            raf1 = new RandomAccessFile(new File("3.png"),"r");
            raf2 = new RandomAccessFile(new File("4.png"),"rw");

            byte[] buffer=new byte[1024];
            int len;
            while((len=raf1.read(buffer))!=-1){
                raf2.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(raf1!=null) {
                try {
                    raf1.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(raf2!=null) {
                try {
                    raf2.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }


    @Test
    public void test2() throws IOException {
        RandomAccessFile raf1 = new RandomAccessFile("hello.txt", "rw");
        raf1.seek(3);
        raf1.write("xyz".getBytes());

    }

    /*
        使用RandomAccessFile实现数据的插入效果
     */

    @Test
    public void test3() throws IOException {
        RandomAccessFile raf1=new RandomAccessFile("hello.txt","rw");

        raf1.seek(3);
        //保存指针3后面的所有数据到一个容器中
        StringBuilder builder=new StringBuilder((int) new File("hello.txt").length());
        byte[] buffer=new byte[20];
        int len;
        while ((len=raf1.read(buffer))!=-1){
            builder.append(new String(buffer,0,len));

        }
        raf1.seek(3);
        raf1.write("xyz".getBytes());

        raf1.write(builder.toString().getBytes());
        raf1.close();
    }

}
posted @ 2022-04-13 14:57  ice--cream  阅读(19)  评论(0编辑  收藏  举报