• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

Dixon_Liang

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

File and IO流

File

package IO;

import org.junit.Test;

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

/**
 *
 * 1. File类的一个对象,代表一个文件或一个文件目录(俗称:文件夹)
 * 2.File类声明在java.io包下
 * 3. File类中涉及到关于文件或文件目录的创建、删除、重命名、修改时间、文件大小等方法,
 *      并未涉及到写入或读取文件内容的操作。如果需要读取或写入文件内容,必须使用To流来完成。
 * 4.后续FiLe类的对象常会作为参数传递到流的构造器中,指明读取或写入的"终点”。
 *
 *
 *
 * 路径分隔符
 *      windows : \
 *      Linux : /
 *
 * @author Dixon
 * @create 2022-06-23 16:40
 */
public class FileTest {

    /**
       1.如何创建FiLe类的实例
            FiLe(String fiLePath)
            FiLe(string parentPath,string childPath)
            FiLe(File parentFiLe,String childPath)

       2.
       相对路径:相较于某个路径下,指明的路径。
       绝对路径:包含盘符在内的文件或文件目录的路径
    */
    @Test
    public void test1(){

        //构造器1
        File file1 = new File("hello.txt"); //相对路径
        File file2 = new File("F:\\java_learn\\高级语言\\src\\IO\\hello.txt"); //绝对路径

        System.out.println(file1);
        System.out.println(file2);

        //构造器2
        File file3 = new File("F:\\java_learn\\高级语言\\src","IO");
        System.out.println(file3);

        //构造器3
        File file4 = new File(file3,"hello.txt");
        System.out.println(file4);
    }

    /**
     * public string getAbsolutePath():获取绝对路径
     * public string getPath() :获取路径
     * public string getName( ) :获取名称
     * public string getParent():获取上层文件目录路径。若无,返回null
     * public long length():获取文件长度(即:字节数)。不能获取目录的长度。
     * public long lastModified() :获取最后一次的修改时间,毫秒值
     */
    @Test
    public void test2(){
        File file1 = new File("hello.txt");//不存在的相对路径
        File file2 = new File("hello1.txt");//确实存在的文件
        File file3 = new File("F:\\java_learn\\高级语言\\src\\IO\\hello.txt");//不存在的绝对路径

        System.out.println("----------1.getAbsolutePath():获取绝对路径-----------");
        System.out.println(file1.getAbsolutePath());
        System.out.println(file2.getAbsolutePath());
        System.out.println(file3.getAbsolutePath());
        System.out.println("--------------2.getPath() :获取路径-----------------");
        System.out.println(file1.getPath());
        System.out.println(file2.getPath());
        System.out.println(file3.getPath());
        System.out.println("--------------3.getName( ) :获取名称-----------------");
        System.out.println(file1.getName());
        System.out.println(file2.getName());
        System.out.println(file3.getName());
        System.out.println("----------4.getParent():获取上层文件目录路径-----------");
        System.out.println(file1.getParent());
        System.out.println(file2.getParent());
        System.out.println(file3.getParent());
        System.out.println("----------5.length():获取文件长度(即:字节数)-----------");
        System.out.println(file1.length());
        System.out.println(file2.length());
        System.out.println(file3.length());
        System.out.println("----------6.lastModified() :获取最后一次的修改时间-----------");
        System.out.println(file1.lastModified());
        System.out.println(file2.lastModified());
        System.out.println(file3.lastModified());
    }

    /**
     * 如下的方法适用于文件目录:
     * public string[] list():获取指定目录下的所有文件或者文件目录的名称数组
     * public File[] listFiles():获取指定目录下的所有文件或者文件目录的File数组
     */
    @Test
    public void test3(){
        File file = new File("F:\\java_learn\\高级语言"); // 必须存在
        String[] list = file.list();
        for (Object o:list) {
            System.out.println(o);
        }


        System.out.println("---------------");


        File[] files = file.listFiles();
        for (File f : files) {
            System.out.println(f);
        }
    }

    /**
     * public boolean renameTo(File dest):把文件重命名为指定的文件路径
     *      比如: file1.renameTo(file2)为例:
     *          要想保证返回true,需要file1在硬盘中是存在的,且fiLe2不能在硬盘中存在。
     */
    @Test
    public void test4(){
        File file1 = new File("hello1.txt");
        File file2 = new File("F:\\java_learn\\高级语言\\src\\IO\\hi.txt");

        boolean b = file2.renameTo(file1);
        System.out.println(b);

    }

    /**
     * public boolean isDirectory():判断是否是文件目录
     * public boolean isFile() :判断是否是文件
     * public boolean exists() :判断是否存在
     * public booLean canRead() :判断是否可读
     * public boolean canWrite() :判断是否可写
     * public boolean isHidden() :判断是否隐藏
     */
    @Test
    public void test5(){
        File file = new File("hello1.txt");
        System.out.println("-----1.public boolean isDirectory():判断是否是文件目录-----------");
        System.out.println(file.isDirectory());
        System.out.println("-----2.public boolean isFile() :判断是否是文件-----------");
        System.out.println(file.isFile());
        System.out.println("-----3.public boolean exists() :判断是否存在-----------");
        System.out.println(file.exists());
        System.out.println("-----4.public booLean canRead() :判断是否可读-----------");
        System.out.println(file.canRead());
        System.out.println("-----5.public boolean canWrite() :判断是否可写-----------");
        System.out.println(file.canWrite());
        System.out.println("-----6.public boolean isHidden() :判断是否隐藏-----------");
        System.out.println(file.isHidden());
    }

    /**
     * 创建硬盘中对应的文件或文件目录:
     * public boolean createNewFile():创建文件。若文件存在,则不创建,返回false
     *
     * 刎除磁盘中的文件或文件目录
     * public booLean delete():删除文件或者文件夹
     *              删除注意事项:
     *                  java中的删除不走回收站。
     */
    @Test
    public void test6() throws IOException {
        File file = new File("he.txt");
        if(!file.exists()){
            file.createNewFile();
            System.out.println("创建成功");
        }else { //文件存在
            file.delete();
            System.out.println("删除成功");
        }
    }

    /**
     * public boolean mkdir() :创建文件目录。如果此文件目录存在,就不创建了。如果此文件目录的上层目录不存在,也不创建。
     * public boolean mkdirs():创建文件目录。如果上层文件目录不存在,一并创建
     */

    @Test
    public void test7() {
        File file1 = new File("F:\\java_learn\\高级语言\\src\\IO\\IO1");
        boolean mkdir = file1.mkdir();
        if(mkdir){
            System.out.println("mkdir创建成功");
        }
        File file2 = new File("F:\\java_learn\\高级语言\\src\\IO\\IO2");
        boolean mkdirs = file2.mkdirs();
        if(mkdirs){
            System.out.println("mkdirs创建成功");
        }

        File file3 = new File("F:\\java_learn\\高级语言\\src\\IO\\IO3");

    }

    /**
     * 练习
     * 1.利用File构造器,new一个文件目录file
     *      1)在其中创建多个文件和目录
     *      2)编写方法,实现删除file中指定文件的操作
     * 2.判断指定目录下是否有后缀名为.jpg的文件,如果有,就输出该文件名称
     * 3.遍历指定目录所有文件名称,包括子文件目录中的文件。
     *      拓展1:并计算指定目录占用空间的大小
     *      拓展2:删除指定文件目录及其下的所有文件
     */
    @Test
    public void test8() throws IOException {
        // 1.利用File构造器,new一个文件目录file
        File file1 = new File("F:\\java_learn\\高级语言\\src\\IO\\IO1\\aaa1.txt");
        //1l创建一个与file同目录下的另外一个文件,文件名为:bbb1.txt
        File file2 = new File(file1.getParent(),"bbb1.txt");
        if (!file2.exists()){
            file2.createNewFile();
            System.out.println("创建成功");
        }
//        else {
//            file2.delete();
//            System.out.println("删除成功");
//        }

       //2.判断指定目录下是否有后缀名为.jpg的文件,如果有,就输出该文件名称
        File file3 = new File(file1.getParent());
        int i =0; //记录多少个文件在此目录下
        for (String s : file3.list()) {
            i++;
            if (s.endsWith(".txt")){
                System.out.println(s);
            }
        }
        System.out.println(i);
    }

    public static void main(String[] args) {
        //3.遍历指定目录所有文件名称,包括子文件目录中的文件。
        File file1 = new File("F:\\java_learn\\高级语言\\src\\IO\\IO1\\aaa1.txt");
        File dir = new File(file1.getParent());
        printSubFile(dir);
        System.out.println("所有容量是:"+ rongLiang);
    }

    //拓展1:并计算指定目录占用空间的大小
    private  static  double rongLiang =0;

    private static void printSubFile(File dir) {
        File[] files = dir.listFiles();
        for (File file : files) {
            if (file.isDirectory()){
                printSubFile(file);
            }else {
                System.out.println(file.getAbsolutePath() + ",容量是:" + file.length());
                rongLiang+= file.length(); //拓展1:并计算指定目录占用空间的大小
            }
        }
    }

    //拓展2:删除指定文件目录及其下的所有文件 未执行,懒得创建
    private static void deleteSubFile(File file) {
        if (file.isDirectory()){ // 如果不是文件目录,那就遍历
            File[]  all = file.listFiles();
            for (File f: all) { // 遍历下一级目录
                deleteSubFile(f); //递归
            }
        }else {
            boolean delete = file.delete();
            if (delete) {
                System.out.println("删除成功");
            }
        }
    }
}

IO流:

package IO.stream;

import org.junit.Test;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 *
 * 一、流的分类
 * ●按操作数据单位不同分为:    字节流(8 bit),字符流(16 bit)
 * ●按数据流的流向不同分为:    输入流,输出流
 * ●按流的角色的不同分为:      节点流,处理流
 *
 *      (抽象基类)      字节流            字符流
 *      输入流         inputStream         Reader
 *      输出流         outputStream        Writer
 *
 * 1. Java的IO流共涉及40多个类,实际上非常规则,都是从如下4个抽象基类派生的。
 * 2.由这四个类派生出来的子类名称都是以其父类名作为子类名后缀。
 *
 *
 * 二、IO流体系:
 *  分类          字节输入流                字节输出流               字符输入流           宁符输出流
 * 抽象基类         inputStream              OutputStream            Reader               Writer
 * 访问文件         FileInputStream          FileOutputStream        FileReader           FileWriter
 * 访问数组         ByteArrayInputStream     ByteArrayOutputStream   CharArrayReader      CharArrayWriter
 * 访问管道         PipedInputStream         PipedOutputStream       PipedReader          PipedWriter
 * 访问宁符串                                                        StringReader         StringWriter
 * 缓冲流(处理流) BufferedInputStream      BufferedOutputStream    BufferedReader       BufferedWriter
 * 转换流                                                          lInputStreamReader   OutputStreamWriter
 * 对象流           ObjectInputStream        ObjectOutputStream
 *                  FilterInputStream        FilterOutputStream      FilterReader         FilterWriter
 * 打印流                                    PrintStream                                   PrintWriter
 * 推回输入流        PushbackInputStream                              PushbackReader
 * 特殊流            DataInputStream         DataOutputStream
 *
 * 处理流之一:缓冲流的使用
 * 1.缓冲流:
 *      BufferedInputStream
 *      BufferedOutputStream
 *      BufferedReader
 *      BufferedWriter
 * 2.作用:提供流的读取、写入的速度
 *
 *
 * @author Dixon
 * @create 2022-06-29 10:27
 */
public class StreamTest{


    /**
     *将src\IO\stream\hello.txt文件内容读入程序中,并输出到控制台
     *
     * 说明点:
     * 1. read()的理解:返回读入的一个字符。如果达到文件末尾,返回-1。
     * 2.异常的处理:为了保证流资源一定可以执行关闭操作。需要使用try-catch-finally处理。
     * 3. 3.读入的文件一定要存在,否则就会报FiLeNotFoundException。
     */
    @Test
    public void testFileReader() {
        FileReader fr = null;
        try {
            //1.实例化File类的对象,指明要操作的文件
            File file = new File("src\\IO\\stream\\hello.txt"); //相较于当前module
//        System.out.println(file.getAbsolutePath()); //F:\java_learn\高级语言\src\IO\stream\hello.txt

            //2.提供具体的流
            fr = new FileReader(file);

            //3.数据的读入,方式一
//        while (true){
//            int read = fr.read(); //read():返回读入的一个字符,如果到了末尾返回-1
//            if(read==-1){
//                break;
//            }
//            System.out.print((char) read);
//        }

            //3.数据的读入,方式二 ,语法上针对于方式一的修改
            int data;
            while ((data =fr.read() )!=-1){
                System.out.print((char)data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.流的关闭操作 必须要执行 所以放到try-catch-finally
            try {
                if(fr !=null){
                    fr.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 对read()操作升级:使用read的重载方法
     */
    @Test
    public void testFileReader1() {
        FileReader fr = null;
        try {
            //1.File类的实例化
            File file =new File("src\\IO\\stream\\hello.txt");

            //2.FileReader流的实例化
            fr = new FileReader(file);

            //3.读入的操作,read(char[]):返回每次读入cbuf数组中的字符个数。如果达到文件末尾,返回-1
            char[] cbuf = new char[5];
            int len;
//        int read = fr.read(cbuf);// 返回 read=5,
            while((len = fr.read(cbuf))!= -1){

                //方式一:
//                for (int i = 0; i < len; i++){ //i<len 最后按照read写入数组的个数去读取
//                    System.out.print(cbuf[i]);
//                }

                //方式二:
//                String str =new String(cbuf);//错误写法
                String str =new String(cbuf,0,len);
                System.out.print(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.资源的关闭
            try {
                if (fr != null){
                    fr.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 从内存中写出数据到硬盘的文件里
     *
     * 说明:
     * 1.输出操作,对应的File可以不存在的。
     *      File对应的硬盘中的文件如果不存在:在输出的过程中,会自动创建此文件。
     *      File对应的硬盘中的文件如果存在:
     *              如果流使用的构造器是:FileWriter(file,false) / FileWriter(file):对原有文件覆盖。
     *              如果流使用的构造器是:FileWriter(file,ture):不会对原有文件覆盖,而是在原有文件末尾追加内容。
     */
    @Test
    public void testFileWriter() {
        FileWriter fw = null;//说明1
        try {
            //1.实例化File类的对象,指明要操作的文件
            File file =new File("src\\IO\\stream\\hello1.txt");//说明1

            //2.提供FileWriter的对象,用于数据的写出
            fw = new FileWriter(file,false);

            //3.写出操作
            fw.write("I have a dream \n");
            fw.write("you also need to have a dream");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.流资源的关闭
            try {
                if (fw!=null) {
                    fw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    public void testFileReaderFileWriter() {
        FileReader fr = null;
        FileWriter fw = null;
        try {
            //1.创建File类的对象,指明读入和写出的文件
            File srcFile = new File("src\\IO\\stream\\hello.txt");
            File desFile = new File("src\\IO\\stream\\hello2.txt");

            //2.创建新入流和输出流的对象
            fr = new FileReader(srcFile);
            fw = new FileWriter(desFile,true); //内容后面追加内容, false才是覆盖

            //3.数据的读入和写出操作
            char[] chars = new char[5];
            int len; //记录每次读入到的chars数组中的字符个数
            while((len=fr.read(chars))!=-1){
                //方式一: 我自己写的
    //            String str = new String(chars,0 ,len);
    ////            System.out.print(str);
    //            fw.write(str);

                //方式二:
                fw.write(chars,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.关闭流资源
            try {
                if(fr != null){
                    fr.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(fw != null){
                    fw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 测试FileInputStream和FileOutputStream的使用
     * 结论:
     * 1.对于文本文件( .txt, .java,.c,.cpp),使用字符流处理
     * 2.对于非文本文件(.jpg,.mp3 ,.mp4 ,.avi,.doc,.ppt, . . .),使用字节流处理
     *
     */
    @Test
    public void testFileInputStream() {
        FileInputStream  fis = null;

        //使用字节流FileInputStream处理文本文件,可能出现乱码。特别是中文
        try {
            //1.造文件
            File file = new File("src\\IO\\stream\\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.关闭资源
            try {
                if (fis!=null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    public void testFileInputOutputStream() {
        FileInputStream  inputStream = null;
        FileOutputStream outputStream = null;
        try {
            File srcFile = new File("F:\\java_learn\\高级语言\\src\\IO\\stream\\111.jpg");
            File desFile = new File("F:\\java_learn\\高级语言\\src\\IO\\stream\\222.jpg");

            inputStream = new FileInputStream(srcFile);
            outputStream = new FileOutputStream(desFile);

            byte[] buffer= new byte[5];
            int len;
            while ((len=inputStream.read(buffer))!=-1){
                outputStream.write(buffer,0,len);
            }
            System.out.println("复制图片成功!");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NumberFormatException e) {
            e.printStackTrace();
        } finally {
            if (inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (outputStream!=null){
                        try {
                            outputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    //指定路径下文件的复制的方法-字节
    public void  copyByteFile(String srcPath , String desPath){
        FileInputStream  inputStream = null;
        FileOutputStream outputStream = null;
        try {
            File srcFile = new File(srcPath);
            File desFile = new File(desPath);

            inputStream = new FileInputStream(srcFile);
            outputStream = new FileOutputStream(desFile);

            byte[] buffer= new byte[1024];
            int len;
            while ((len=inputStream.read(buffer))!=-1){
                outputStream.write(buffer,0,len);
            }
            System.out.println("复制图片或视频成功!");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NumberFormatException e) {
            e.printStackTrace();
        } finally {
            if (inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (outputStream!=null){
                        try {
                            outputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    @Test //对上面方法进行测试
    public void testCopyByteFile(){
        long start = System.currentTimeMillis();
        String fileA ="F:\\java_learn\\高级语言\\src\\IO\\stream\\testA.mkv";
        String fileB ="F:\\java_learn\\高级语言\\src\\IO\\stream\\testB.mkv";
        copyByteFile(fileA,fileB);
        long end = System.currentTimeMillis();
        System.out.println("复制图片需要的时间为:"+ (end-start)); //时间1284
    }

    /**
     * 缓冲流
     * 实现非文本文件的复制
     */
    @Test //处理流-缓冲流-字节(非文本文件)
    public void testBufferedStreamTest()  {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            //1 造文件
            File srcFile = new File("src\\IO\\stream\\111.jpg");
            File destFile = new File("src\\IO\\stream\\333.jpg");

            //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[5];
            int len;
            while ((len= bis.read(buffer))!=-1){
                    bos.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4 关闭流--要求先关外层的流,在关闭内层的流,关闭外层流的同时内层流也会自动关闭,省略关闭内层流

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

    //指定路径下文件的复制的方法-字节 +缓冲流(非文本文件)
    public void  bufferedCopyByteFile(String srcPath , String desPath){
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            //1 造文件
            File srcFile =  new File(srcPath);
            File destFile = new File(desPath);

            //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 关闭流--要求先关外层的流,在关闭内层的流,关闭外层流的同时内层流也会自动关闭,省略关闭内层流

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

    }

    @Test //对上面方法进行测试
    public void testBufferedCopyByteFile(){
        long start = System.currentTimeMillis();
        String fileA ="F:\\java_learn\\高级语言\\src\\IO\\stream\\testA.mkv";
        String fileB ="F:\\java_learn\\高级语言\\src\\IO\\stream\\testC.mkv";
        bufferedCopyByteFile(fileA,fileB);
        long end = System.currentTimeMillis();
        System.out.println("复制图片需要的时间为:"+ (end-start)); //306

    }

    @Test//字符-处理流复制
    public void testBufferedReadBufferedWriter() {
        BufferedReader bfr = null;
        BufferedWriter bfw = null;
        try {
            //1造文件
            File srcFile = new File("src\\IO\\stream\\hello.txt");
            File destFile = new File("src\\IO\\stream\\hello4.txt");

            //2.1 创建节点流
            FileReader fir = new FileReader(srcFile);
            FileWriter fiw = new FileWriter(destFile);
            //2.2 创建处理流
            bfr = new BufferedReader(fir);
            bfw = new BufferedWriter(fiw);
            //方式一:
//            char[] chars = new char[5];
//            int len;
//            while ((len=bfr.read(chars))!=-1){
//                bfw.write(chars,0,len);
//            }

            //方式二:试用String
            String data;
            while ((data=bfr.readLine())!=null){ //readLine 不包括换行符
                //方法1:
//                bfw.write(data + "\n");
                //方法2:
                bfw.write(data);
                bfw.newLine();
            }
            System.out.println("复制成功!");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            //3 关闭外层流
            try {
                if(bfr!=null){
                    bfr.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(bfw!=null){
                    bfw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Test//给图片/视频加密
    public void testPictureSecret(){
        BufferedInputStream bfs = null;
        BufferedOutputStream bos = null;
        try {
            FileInputStream  fips = new FileInputStream("F:\\java_learn\\高级语言\\src\\IO\\stream\\testA.mkv");
            FileOutputStream fops = new FileOutputStream("F:\\java_learn\\高级语言\\src\\IO\\stream\\testSecret.mkv");

            bfs = new BufferedInputStream(fips);
            bos = new BufferedOutputStream(fops);


            byte[] bytes = new byte[20];
            int len;
            while ((len = bfs.read(bytes))!=-1){

                //字节加密
                for (int i = 0; i < len; i++) {
                    bytes[i] = (byte) (bytes[i] ^ 5);

                }
                bos.write(bytes,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bfs!=null){
                try {
                    bfs.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

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

        }
    }

    @Test//给图片/视频-解密
    public void testPictureDecry(){
        BufferedInputStream bfs = null;
        BufferedOutputStream bos = null;
        try {
            FileInputStream  fips = new FileInputStream("F:\\java_learn\\高级语言\\src\\IO\\stream\\testSecret.mkv");
            FileOutputStream fops = new FileOutputStream("F:\\java_learn\\高级语言\\src\\IO\\stream\\testDecry.mkv");

            bfs = new BufferedInputStream(fips);
            bos = new BufferedOutputStream(fops);


            byte[] bytes = new byte[20];
            int len;
            while ((len = bfs.read(bytes))!=-1){

                //字节解密, 加密异或了5 再次异或5又变回原来哦,,神奇。
                for (int i = 0; i < len; i++) {
                    bytes[i] = (byte) (bytes[i] ^ 5);

                }
                bos.write(bytes,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bfs!=null){
                try {
                    bfs.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

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

        }

    }

    @Test//获取文本上每个字符出现得次数
    public void testAddCount(){
        BufferedReader bfr = null;
        BufferedWriter bfw = null;
        try {
            bfr = new BufferedReader(new FileReader("F:\\java_learn\\高级语言\\src\\IO\\stream\\hello.txt"));
            Map<Character, Integer> map = new HashMap<>();
            char[] chars = new char[5];
            int len;
            while ((len = bfr.read(chars)) != -1) {
    //            System.out.println(len);
                for (int i = 0; i < len; i++) {
    //                System.out.println(chars[i]);
                    char c = Character.toLowerCase(chars[i]);
                    if(map.containsKey(c)){
                        map.put(c, (map.get(c)+1) );
                    }else {
                        map.put(c,1);
                    }
                }
            }
//        System.out.println(map); //输出map 康康
            bfw = new BufferedWriter(new FileWriter("F:\\java_learn\\高级语言\\src\\IO\\stream\\hello5.txt"));
            Set<Map.Entry<Character, Integer>> entries = map.entrySet();
            for (Map.Entry<Character, Integer> entry: entries) {
                switch (entry.getKey()){
                    case ' ':
                        bfw.write("空格=" + entry.getValue());
                        break;
                    case'\t':
                        bfw.write("制表符tab=" + entry.getValue());
                        break;
                    case'\r':
                        bfw.write("回车=" + entry.getValue());
                        break;
                    case'\n':
                        bfw.write("换行=" + entry.getValue());
                        break;
                    default:
                        bfw.write(entry.getKey()+"=" + entry.getValue());
                        break;
                }
                bfw.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bfr!=null){
                try {
                    bfr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bfw!=null){
                try {
                    bfw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 处理流之二:转换流的使用
     * 1.转换流属于字符流
     * 2.转换流提供了在字节流和字符流之间的转换Ⅰ
     * Java API提供了两个转换流:
     *      InputStreamReader:   将一个字节的输入流转换为字符的输入流 ,将InputStream转换为Reader
     *      OutputStreamWriter:将一个字符的输出流转换为字节的翰出流, 将Writer转换为OutputStream
     * 3.   InputStreamReader--->解码:字节、字节数组--->字符数组、字符串
     *      OutputStreamWriter-->编码:字符数组、字符串--->字节、字节数组
     * 字节流中的数据都是字符时,转成字符流操作更高效。
     * 很多时候我们使用转换流来处理文件乱码问题。实现编码和解码的功能。
     *
     */
    @Test// 捕获异常偷懒了.应该用try-catch-finally
    public void testSwitchStream() throws IOException {

        //InputStreamReader
        FileInputStream fis = new FileInputStream("F:\\java_learn\\高级语言\\src\\IO\\stream\\hello.txt");
//        InputStreamReader isr = new InputStreamReader(fis);//使用系统默认的字符集
        //参数2指明字符集,具体使用哪个字符集,取决于文件保存时使用的字符集
        InputStreamReader isr = new InputStreamReader(fis,"UTF-8");

        //OutputStreamWriter
        FileOutputStream fos = new FileOutputStream("F:\\java_learn\\高级语言\\src\\IO\\stream\\hello6-jdk.txt");
        OutputStreamWriter osw = new OutputStreamWriter(fos,"gbk");

        //读写过程
        char[] chars= new char[5];
        int len;
        while ((len=isr.read(chars))!=-1){
            String str = new String(chars,0,len);
//            System.out.print(str);
            osw.write(chars,0,len);
        }
        isr.close();
        osw.close();
    }

    /**
     *字符集:了解
     *
     * 编码表的由来:
     *          计算机只能识别二进制数据,早期由来是电信号。为了方便应用计算机,让它可以识别各个国家的文字。就将各个国家的文字用数字来表示,
     *          并一一对应,形成一张表。这就是编码表。
     * 常见的编码表:
     * ASCII:美国标准信息交换码。
     *      用一个字节的7位可以表示。
     *ISO8859-1:拉丁码表。欧洲码表
     *      用一个字节的8位表示。
     * GB2312:
     *      中国的中文编码表。最多两个字节编码所有字符
     * GBK:
     *      中国的中文编码表升级,融合了更多的中文文字符号。最多两个字节编码
     *Unicode:
     *      国际标准码,融合了目前人类使用的所有字符。为每个字符分配唯一的字符码。所有的文字都用两个字节来表示。
     * UTF-8:
     *      变长的编码方式,可用1-4个字节来表示一个字符.
     *
     */

 

posted on 2022-06-30 22:16  Dixon_Liang  阅读(33)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3