栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java笔记21-Java高级编程部分-第十三章-IO流

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java笔记21-Java高级编程部分-第十三章-IO流

第13章:IO流

目录:


13.1、File类的使用








FileTest

package com.pfl.java3;

import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.util.Date;


public class FileTest {

    
    @Test
    public void test1() {

        //构造器1:
        File file1 = new File("hello.txt");  //相对于当前的Module
        File file2 = new File("D:\Software\Java\WorkSpace\workspace-idea1\day08\hello.txt");  //相对于当前的Module

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

        //构造器2:
        File file3 = new File("D:\Software","Java");
        System.out.println(file3);

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

    }

    
    @Test
    public void test2() {
        File file1 = new File("hello.txt");
        File file2 = new File("D:\Software\Java\WorkSpace\io\hello.txt");

        System.out.println(file1.getAbsolutePath());
        System.out.println(file1.getPath());
        System.out.println(file1.getName());
        System.out.println(file1.getParent());
        System.out.println(file1.length());
        System.out.println(new Date(file1.lastModified()));

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

        System.out.println(file2.getAbsolutePath());
        System.out.println(file2.getPath());
        System.out.println(file2.getName());
        System.out.println(file2.getParent());
        System.out.println(file2.length());
        System.out.println(file2.lastModified());
    }
    @Test
    public void test3() {
        File file = new File("D:\Software\Java\WorkSpace\workspace-idea1");

        String[] list = file.list();
        for(String s : list) {
            System.out.println(s);
        }

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

    
    @Test
    public void test4() {
        File file1 = new File("hello.txt");
        File file2 = new File("D:\Software\Java\WorkSpace\io\hi.txt");

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

    
    @Test
    public void test5() {
        File file1 = new File("hello.txt");

        System.out.println(file1.isDirectory());
        System.out.println(file1.isFile());
        System.out.println(file1.exists());
        System.out.println(file1.canRead());
        System.out.println(file1.canWrite());
        System.out.println(file1.isHidden());
        System.out.println("*************************");

        file1 = new File("hello1.txt");

        System.out.println(file1.isDirectory());
        System.out.println(file1.isFile());
        System.out.println(file1.exists());
        System.out.println(file1.canRead());
        System.out.println(file1.canWrite());
        System.out.println(file1.isHidden());
        System.out.println("*************************");

        File file2 = new File("D:\Software\Java\WorkSpace\io");

        System.out.println(file2.isDirectory());
        System.out.println(file2.isFile());
        System.out.println(file2.exists());
        System.out.println(file2.canRead());
        System.out.println(file2.canWrite());
        System.out.println(file2.isHidden());
        System.out.println("*************************");

    }

    

    @Test
    public void test6() throws IOException {
        //文件的创建
        File file1 = new File("hi.txt");
        if(!file1.exists()) {
            file1.createNewFile();
            System.out.println("创建成功!");
        } else { //文件存在
            file1.delete();
            System.out.println("删除成功");
        }
    }

    //文件目录的创建
    @Test
    public void test7() {
        //文件目录的创建
        File file1 = new File("D:\Software\Java\WorkSpace\io\io1\io3");

        boolean mkdir = file1.mkdir();
        if(mkdir) {
            System.out.println("创建成功1");
        }

        File file2 = new File("D:\Software\Java\WorkSpace\io\io1\io4");

        boolean mkdir2 = file1.mkdirs();
        if(mkdir2) {
            System.out.println("创建成功2");
        }

        //要是想要删除成功,文件目录子目录下不能有子目录或文件
        File file3 = new File("D:\Software\Java\WorkSpace\io\io1\io3");
        file3 = new File("D:\Software\Java\WorkSpace\io");
        System.out.println(file3.delete());
    }
}


练习:


FileDemo

package com.pfl.exer2;

import org.junit.Test;

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


public class FileDemo {

    @Test
    public void test1() throws IOException {

        File file = new File("D:\Software\Java\WorkSpace\io\io1\hello.txt");
        //创建一个 与file同目录下的另一个文件,文件名为:haha.txt
        File destFile = new File(file.getParent(), "haha.txt");
        boolean newFile = destFile.createNewFile();
        if (newFile) {
            System.out.println("创建成功!");
        }
    }
}

FindGPJFileTest:

package com.pfl.exer2;

import org.junit.Test;

import java.io.File;
import java.io.FilenameFilter;


public class FindGPJFileTest {

    @Test
    public void test1() {
        File srcFile = new File("D:\Software\Java\WorkSpace\io");

        String[] fileNames = srcFile.list();
        for (String fileName : fileNames) {
            if (fileName.endsWith(".jpg")) {
            System.out.println(fileName);
            }
        }
    }

    @Test
    public void test2() {
        File srcFile = new File("D:\Software\Java\WorkSpace\io");

        File[] listFiles = srcFile.listFiles();
        for (File listFile : listFiles) {
            if (listFile.getName().endsWith(".jpg")) {
                System.out.println(listFile.getAbsolutePath());
            }
        }
    }
    
    @Test
    public void test3() {
        File srcFile = new File("D:\Software\Java\WorkSpace\io");

        File[] subFiles = srcFile.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".jpg");
            }
        });

        for (File file:subFiles) {
            System.out.println(file.getAbsolutePath());
        }
    }
}

ListFileTest:

package com.pfl.exer2;

import java.io.File;


public class ListFilesTest {

    public static void main(String[] args) {
        //递归:文件目录
        
        //1.创建目录对象
        File dir = new File("D:\Software\Java\WorkSpace\io");

        //2.打印目录的子文件
        printSubFile(dir);
    }

    public static void printSubFile(File dir) {
        //打印目录的子文件
        File[] subfiles = dir.listFiles();

        for (File f : subfiles) {
            if (f.isDirectory()) {  //文件目录
                printSubFile(f);
            } else {
                System.out.println(f.getAbsolutePath());
            }
        }
    }

    //方式二:循环实现
    //列出file目录下的下级内容,仅列出一级的话
    //使用File类的String[] list()比较简单
    public void listSubFiles(File file) {
        if (file.isDirectory()) {
            String[] all = file.list();
            for (String s : all) {
                System.out.println(s);
            }
        } else {
            System.out.println(file + "是文件!");
        }
    }

    //列出file目录的下级,如果它的下级还是目录,接着列出下级的下级,依次类推
    // 建议使用FiLe类的FiLe[] listFiles()
    public void listAllSubFiles(File file) {
        if (file.isFile()) {
            System.out.println(file);
        } else {
            File[] all = file.listFiles();
            //如果all[i]是文件,直接打印
            //如果all[i]是目录,接着再获取它的下一级
            for (File f : all) {
                listAllSubFiles(f);  //递归调用:自己调用自己就叫递归
            }
        }
    }

    //扩展1:求指定目录所在空间的大小
    //求任意一个目录的总大小
    public long getDirectorySize(File file) {
        //file是文件,那么直接返回file.length()
        //file是目录,把它的下一级的所有大小加起来就是它的总大小
        long size = 0;
        if (file.isFile()) {
            size += file.length();
        }else {
            File[] all = file.listFiles();//获取fiLe的下一级
            // 累加all[i]的大小
            for (File f : all) {
                size += getDirectorySize(f);// f的大小;
            }
        }
        return size;
    }

    //拓展2:删除指定的目录
    public void deleteDirectory (File file) {
        //如果file是文件,直接delete
        //如果fiLe是目录,先把它的下一级干掉,然后删除自己
        if (file.isDirectory()) {
            File[] all = file.listFiles();
            //循环删除的是file的下一级
            for (File f : all) {// f代表file的每一个下级
                deleteDirectory(f);
            }
        }
        //删除自己
        file.delete();
    }

}
每日一练: 1.如何遍历Map 的key集,value集, key-value集,使用上泛型。



2.写出使用Iterator和增强for循环遍历List的代码,使用上泛型。 3.提供一个方法,用于遍历获取HashMap中的所有value,并存放在List中返回。考虑上集合中泛型的使用。

4.创建一个与a.txt文件同目录下的另外一个文件b.txt。

5.Map接口中的常用方法有哪些。

13.2、IO流原理及流的分类







注:垃圾回收机制的关键点:

FileReaderWriterTest:

package com.pfl.java;

import org.junit.Test;

import java.io.*;


public class FileReaderWriterTest {

    public static void main(String[] args) {

        File file = new File("hello.txt");  //相较于当前工程下
        System.out.println(file.getAbsolutePath());

        File file1 = new File("day09\hello.txt");
        System.out.println(file1.getAbsolutePath());
    }

    

    @Test
    public void testFileReader(){
        FileReader fileReader = null;
        try {
            //1.实例化File类的对象,指明要操作的文件
            File file = new File("hello1.txt");  //相较于当前的Module下
            //2.提供具体的流
            fileReader = new FileReader(file);

            //3.数据的读入过程
            //read():返回读入的一个字符。如果达到文件末尾,返回-1

            //方式一:
//        int data = fileReader.read();
//        while(data != -1) {
//            System.out.print((char) data);
//            data = fileReader.read();
//        }
            //方式二:语法上针对于方式一的修改
            int data;
            while((data = fileReader.read()) != -1) {
                System.out.print((char) data);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.流的关闭操作
//            try {
//                if (fileReader != null)
//                    //如果在实例化之前就出现了异常,直接就会跳到finally,没就无需再close了
//                    fileReader.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
            //或
            if (fileReader != null) {
                //如果在实例化之前就出现了异常,直接就会跳到finally,没就无需再close了
                try {
                    fileReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //注:针对于还有一定要执行的操作,需要使用try...catch...finally
        }
    }

    //对read()操作升级:使用read的重载方法
    @Test
    public void testFileReader1(){
        //注:try-catch-finally + synchronized ...快捷键:ctrl + alt + T
        FileReader fr = null;
        try {
            //1.File类的实例化
            File file = new File("hello.txt");

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

            //3.读入的操作  ---下面有一个难点
            //read(char[] cbuffer):返回每次读入cbuffer数组中的字符的个数。如果到达文件末尾,返回-1
            char[] cbuf = new char[5];
            int len;
            while ((len = fr.read(cbuf)) != -1) {
                //方式一:
                //错误的写法:
//                for (int i = 0;i < cbuf.length;i++) {
//                    System.out.println(cbuf[i]);
//                }
                //正确的写法
//                for (int i = 0;i < len;i++) {
//                    System.out.print(cbuf[i]);
//                }


                //方式二:--错误的写法--对应着方式一的错误的写法
//                String str = new String(cbuf);
//                System.out.print(str);
                //注:遇到一个问题,不知道为什么会报红:
// "String()' in 'com.sun.org.apache.xpath.internal.operations.String' cannot be applied to '(charD)"
                //解决方法:删除“com.sun.org.apache.xpath.internal.operations.String”---这是上面导入的包

                //正确的写法:
                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();
                }
            }
        }

    }

    
    @Test
    public void testFileWriter(){
        FileWriter fw = null;
        try {
            //1.提供File类的对象,指明写出到的文件
            File file = new File("hello1.txt");

            //2.提供FileWriter的对象,用于文件的写出
            //FileWriter的第二个参数,表示是否添加(追加)
            fw = new FileWriter(file,false);

            //3.写出的具体的操作
            fw.write("I have a dream!n");
            //调用数组的方法
//        fw.write("I have a dream!".toCharArray());
            //可以在继续写出
            fw.write("you need to have a dreamn");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fw != null) {
                //4.流资源的关闭
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    //注:快捷键:ctrl + alt + T:try-catch-finally
    @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; //记录每次读入到cbuf数组中的字符的个数
            while ((len = fr.read(cbuf)) != -1) {
                //每次写出len个字符
                fw.write(cbuf,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.关闭流资源
            //方式一:
//            try {
//                if (fr != null)
//                    fr.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            } finally {
//                try {
//                    if(fw != null)
//                        fw.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }

            //方式二:try-catch并不影响后面的程序的运行
            try {
                if (fr != null)
                    fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(fw != null)
                    fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

FileInputOutputStreamTest:

package com.pfl.java;

import org.junit.Test;

import java.io.*;


public class FileInputOutputStreamTest {
    //使用字节流FileInputStream处理文本文件,可能会出现乱码。
    @Test
    public void testFileInputStream(){
        FileInputStream fis = null;

        try {
            //1.造文件
            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 {
            if(fis != null) {
                //4.关闭资源
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    
    @Test
    public void testFileInputOutputStream() {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            //
            File srcfile = new File("浅绿色壁纸.jpg");
            File destfile = new File("浅绿色壁纸2.jpg");

            //
            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 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() {

        long start = System.currentTimeMillis();

        String srcPath = "F:\图片\桌面图片\小姐姐.mp4";
        String destPath = "F:\图片\桌面图片\小姐姐2.mp4";

        //注:不经过内存转化(就是不需要输出出来,直接复制到另外一个文件)是不会出现问题的
//        String srcPath = "hello.txt";
//        String destPath = "hello3.txt";

        copyFile(srcPath,destPath);

        long end = System.currentTimeMillis();
        System.out.println("复制操作花费的时间为:" + (end - start));  //85
    }
}

BufferTest:

package com.pfl.java;

import org.junit.Test;

import java.io.*;



public class BufferTest {

    
    @Test
    public void BufferedStreamTest() {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        try {
            //1.造文件
            File srcFile = new File("浅绿色壁纸.jpg");
            File destFile = new File("浅绿色壁纸2.jpg");

            //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[10];
            int len;
            while((len = bis.read(buffer)) != -1) {
                bos.write(buffer, 0 ,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.关闭流
            //要求:先关闭外层的流,在关闭内层的流
            if(bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //说明:在关闭外层流的同时,内层流也会自动的进行关闭。关于内层流的关闭,我们可以省略
//        fis.close();
//        fos.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[10];
            int len;
            while((len = bis.read(buffer)) != -1) {
                bos.write(buffer, 0 ,len);

//                bos.flush();  //刷新缓冲区
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.关闭流
            //要求:先关闭外层的流,在关闭内层的流
            if(bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //说明:在关闭外层流的同时,内层流也会自动的进行关闭。关于内层流的关闭,我们可以省略
//        fis.close();
//        fos.close();
        }
    }

    @Test
    public void testCopyFileWithBuffered() {
        long start = System.currentTimeMillis();

        String srcPath = "D:\life\photo\桌面图片\小姐姐.mp4";
        String destPath = "D:\life\photo\桌面图片\小姐姐2.mp4";


        copyFileWithBuffered(srcPath,destPath);

        long end = System.currentTimeMillis();
        System.out.println("复制操作花费的时间为:" + (end - start));  //15--21
    }

    
    @Test
    public void testBufferedReaderBufferedWriter() {
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            //造文件造流放在一起解决
            //创建文件和相应的流
            br = new BufferedReader(new FileReader(new File("hello.txt")));
            bw = new BufferedWriter(new FileWriter(new File("hello1.txt")));

            //BufferedReader和BufferedWriter多了一种方案---区别于前面的FileReader和FileWriter
            //读写操作
            //方式一:
//            char[] cbuf = new char[1024];
//            int len;
//            while((len = br.read(cbuf)) != -1) {
//                bw.write(cbuf, 0, len);
//    //            bw.flush();  //当达到缓存的大小的时候,自动会进行flush()
//            }
            //方式二:使用String
            String data;
            while((data = br.readLine()) != null) {
                //方法一:
//                bw.write(data + "n");  //data中不包含换行符
                //方法二:
                bw.write(data);  //data中不包含换行符
                bw.newline();  //提供换行的操作
            }


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

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

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

    }
}
练习:


T2:

package com.pfl.exer;

import org.junit.Test;

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

/**
 * @author pflik-
 * @create 2021-10-06 19:39
 */
public class PicTest {

    //图片的加密---使用字节流---这是一个可逆的过程,还是可以继续解密的
    @Test
    public void test1() {
        FileInputStream fis = null;
        FileOutputStream fos = null;

        try {
//        FileInputStream fis = new FileInputStream(new File("IU.jpg"));

            //其实是把字符串包装成了文件
            fis = new FileInputStream(new File("IU.jpg"));
            fos = new FileOutputStream("IU-secret.jpg");

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

                //对字节数据进行修改
                //注意:增强for循环改的是一个临时的变量,buffer数组并没有改--一个错误的演示
    //            for(byte b : buffer) {
    //                b = (byte) (b ^ 5);
    //            }
                //正确的--对字节数上的每个位置上的字节做了异或运算
                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 {
//        FileInputStream fis = new FileInputStream(new File("IU.jpg"));

            //其实是把字符串包装成了文件
            fis = new FileInputStream(new File("IU-secret.jpg"));
            fos = new FileOutputStream("IU2.jpg");

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

                //对字节数据进行修改
                //注意:增强for循环改的是一个临时的变量,buffer数组并没有改--一个错误的演示
                //            for(byte b : buffer) {
                //                b = (byte) (b ^ 5);
                //            }
                //正确的--对字节数上的每个位置上的字节做了异或运算
                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();
                }
            }
        }

    }
}

T3:

package com.pfl.exer;

import org.junit.Test;

import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 *
 *  练习3:获取文本上字符出现的次数,把数据写入文件
 *
 *  思路:
 *    1.遍历文本每一个字符
 *    2.字符出现的次数存在Map中
 *    Map map = new HashMap();
 *    map.put('a', 18);
 *    map.put('你', 2);
 *    3.把map中的数据写入文件
 *
 *
 * @author pflik-
 * @create 2021-10-06 20:07
 */
public class WordCount {

    /*
    说明:如果使用单元测试,文件相对路径为当前module
            如果使用main()测试,文件相对路径为当前工程
     */
    @Test
    public void testWordCount() {
        FileReader fr = null;
        BufferedWriter bw = null;

        try {
            //1.创建map集合
            Map map = new HashMap<>();

            //2.遍历每一个字符,每一个字符出现的次数放到map中
            fr = new FileReader("hello.txt");

            int c = 0;
            while((c = fr.read()) != -1) {
                //int 还原 char
                char ch = (char)c;

                //判断char是否在map中第一次出现
                if(map.get(ch) == null) {
                    map.put(ch, 1);
                } else {
                    map.put(ch, map.get(ch) + 1);
                }
            }
            //3.把map中数据存在文件count.txt
            //3.1 创建Writer
            bw = new BufferedWriter(new FileWriter("wordcount.txt"));

            //3.2 遍历map,再写入数据
            Set> entrySet = map.entrySet();
            for(Map.Entry entry : entrySet) {
                switch (entry.getKey()) {
                    case ' ':
                        bw.write("空格=" + entry.getValue());
                        break;
                    case 't':  //t表示tab键字符
                        bw.write("tab键=" + entry.getValue());
                        break;
                    case 'r':  //
                        bw.write("回车=" + entry.getValue());
                        break;
                    case 'n':  //
                        bw.write("换行=" + entry.getValue());
                        break;
                    default:
                        bw.write(entry.getKey() + "=" + entry.getValue());
                        break;
                }
                bw.newline();  //换行
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

13.5、转换流–处理流的一种





InputStreamReader:

package com.pfl.java;

import org.junit.Test;

import java.io.*;


public class InputStreamReaderTest {

    
    @Test
    public void test1() {
        InputStreamReader isr = null;  //使用系统默认的字符集

        try {
            //选择使用字节流
            FileInputStream fis = new FileInputStream("hello.txt");

            isr = new InputStreamReader(fis);

            //参数2:指明字符集,具体使用哪个字符集,取决于文件保存时使用的字符集
//            InputStreamReader 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() {
        FileInputStream fis = null;
        FileOutputStream fos = null;

        try {
            //1.造文件,造流
            File file1 = new File("hello.txt");
            File file2 = new File("hello_gbk.txt");

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

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

            //2.读写过程
            char[] cbuf = new char[20];
            int len;
            while ((len = isr.read(cbuf)) != -1) {
                osw.write(cbuf, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //3.关闭资源
            if(fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}



13.6、标准输入、输出流




OtherStreamTest:

package com.pfl.java;

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


public class OtherStreamTest {

    
    //注:如果使用单元测试,是无法使用键盘输入的,所以改成了在main方法中
//    @Test
//    public void test1() {
    public static void main(String[] args) {
        BufferedReader br = null;

        try {
            //转换流
            InputStreamReader isr = new InputStreamReader(System.in);

            br = new BufferedReader(isr);

            while(true) {
                System.out.println("请输入字符串:");
                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();
                }
            }
        }


    }
}


MyInput:

package com.pfl.exer;

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


public class MyInput {

    public static String readString() {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        //Declare and initialize the string
        String string = "";

        //Get the string from the keyboard
        try {
            string = br.readLine();
        } catch (IOException e) {
            System.out.println(e);
        }

        //Return the string obtained from the keyboard

        return string;
    }

    //Read an int value from the keyboard
    public static int readInt() { return Integer.parseInt(readString()); }

    //Read a double value from the keyboard
    public static double readDouble() { return Double.parseDouble(readString()); }

    //Read a byte value from the keyboard
    public static double readByte() { return Byte.parseByte(readString()); }

    //Read a short value from the keyboard
    public static double readShort() { return Short.parseShort(readString()); }

    //Read a long value from the keyboard
    public static double readLong() { return Long.parseLong(readString()); }

    // Read a float value from the keyboard
    public static double readFloat() { return Float.parseFloat(readString()); }
    
}

13.7、打印流



13.8、数据流


package com.pfl.java;

import org.junit.Test;

import java.io.*;


public class OtherStreamTest {

    
    //注:如果使用单元测试,是无法使用键盘输入的,所以改成了在main方法中
//    @Test
//    public void test1() {
    public static void main(String[] args) {
        BufferedReader br = null;

        try {
            //转换流
            InputStreamReader isr = new InputStreamReader(System.in);

            br = new BufferedReader(isr);

            while(true) {
                System.out.println("请输入字符串:");
                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();
                }
            }
        }
    }

    

    
    @Test
    public void test3() {

        DataOutputStream dos = null;
        try {
            dos = new DataOutputStream(new FileOutputStream("data.txt"));

            dos.writeUTF("刘建辰");
            dos.flush();
            dos.writeInt(23);
            dos.flush();
            dos.writeBoolean(true);
            dos.flush();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(dos != null) {
                try {
                    dos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    @Test
    public void test4() {
        DataInputStream dis = null;

        try {
            //1.
            dis = new DataInputStream(new FileInputStream("data.txt"));
            //2.
            String name = dis.readUTF();
            int age = dis.readInt();
            boolean isMale = dis.readBoolean();

            System.out.println("name = " + name);
            System.out.println("age = " + age);
            System.out.println("isMale = " + isMale);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(dis != null) {
                try {
                    dis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

每日一练:

1.
2.





13.9、对象流




ObjectInputOutputStreamTest:

package com.pfl.java;

import org.junit.Test;

import java.io.*;


public class ObjectInputOutputStreamTest {

    
    @Test
    public void testObjectOutputStream() {
        ObjectOutputStream oos = null;

        try {
            //1.造流造文件
            oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
            //2.写出的过程
            oos.writeObject(new String("我爱北京天安门"));

            oos.flush();  //刷新操作
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(oos != null) {
                //3.关闭流
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    
    @Test
    public void testObjectInputStream() {

        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new FileInputStream("object.dat"));

            Object obj = ois.readObject();
            String str = (String) obj;
            System.out.println(str);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if(ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}


Person:

package com.pfl.java;

import java.io.Serializable;


public class Person implements Serializable {

    public static final long serialVersionUID = 43242313465L;

    private String name;
    private int age;
    private int id;
    private Account acct;

    //注:构造器,get,set方法快捷键 ----> alt + ins


    public Person(String name, int age, int id, Account acct) {
        this.name = name;
        this.age = age;
        this.id = id;
        this.acct = acct;
    }

    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Person(String name, int age, int id) {
        this.name = name;
        this.age = age;
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + ''' +
                ", age=" + age +
                ", id=" + id +
                ", acct=" + acct +
                '}';
    }
}

class Account implements Serializable{

    public static final long serialVersionUID = 43242313465L;

    private double balance;

    public Account(double balance) {
        this.balance = balance;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }

    @Override
    public String toString() {
        return "Account{" +
                "balance=" + balance +
                '}';
    }
}

ObjectInputOutputStreamTest:

package com.pfl.java;

import org.junit.Test;

import java.io.*;


public class ObjectInputOutputStreamTest {

    
    @Test
    public void testObjectOutputStream() {
        ObjectOutputStream oos = null;

        try {
            //1.造流造文件
            oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
            //2.写出的过程
            oos.writeObject(new String("我爱北京天安门"));
            oos.flush();  //刷新操作

            oos.writeObject(new Person("王明", 23));
            oos.flush();

            oos.writeObject(new Person("张学良", 23, 1001, new Account(5000)));
            oos.flush();


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(oos != null) {
                //3.关闭流
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    
    @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();
                }
            }
        }
    }
}
13.10、随机存取文件流




视频617:6.30–

package com.pfl.java;

import org.junit.Test;

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

/**
 *  RandomAccessFile的使用
 *  1.RandomAccessFile直接继承于java.lang.Object类,实现了DataInput和DataOutput接口
 *  2.RandomAccessFile既可以作为一个输入流,又可以作为一个输出流
 *
 *  3.如果RandomAccessFile作为输出流时,写出到的文件如果不存在,则在执行过程中自动创建
 *  如果写出到的文件存在,则会对原有文件内容进行覆盖。(默认情况下,从头覆盖)
 *
 * @author pflik-
 * @create 2021-10-09 16:30
 */
public class RandomAccessFileTest {

    @Test
    public void test1() {

        RandomAccessFile raf1 = null;
        RandomAccessFile raf2 = null;
        try {
            //1.造流的对象
            raf1 = new RandomAccessFile(new File("IU.jpg"), "r");
            raf2 = new RandomAccessFile(new File("IU1.jpg"), "rw");
            //2.读写过程
            byte[] buffer = new byte[1024];
            int len;
            while((len = raf1.read(buffer)) != -1) {
                raf2.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //3.关闭流
            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() {
        RandomAccessFile raf1 = null;
        try {
            raf1 = new RandomAccessFile("hello.txt", "rw");

            raf1.seek(3);  //将指针调到角标为3的位置,然后覆盖后面的内容

            raf1.write("xyz".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(raf1 != null) {
                try {
                    raf1.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /*
    使用RandomAccessFile实现数据的插入效果
     */
    @Test
    public void test3() {
        RandomAccessFile raf1 = new RandomAccessFile("hello.txt", "rw");

        raf1.seek(3);  //将指针调到角标为3的位置,然后覆盖后面的内容

        //有可能是好多行
        byte[] buffer = new byte[20];

    }
}


ByteArrayOutputStreamTest.java

package com.pfl.java;


import org.junit.Test;

import java.io.*;
import java.nio.Buffer;

public class ByteArrayOutputStreamTest {

    @Test
    public void test1() throws IOException {
        FileInputStream fis = new FileInputStream("abc.txt");
        String info = readStringFromInputStream(fis);
        System.out.println(info);
    }
    private String readStringFromInputStream(FileInputStream fis) throws IOException {
        //方式一:可能出现乱码
//        String content = "";
//        byte[] buffer = new byte[1024];
//        int len;
//        while((len = fis.read(buffer)) != 1) {
//            content += new String(buffer);
//        }
//        return content;

        //方式二:BufferedReader
        BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
        char[] buf = new char[10];
        int len;
        String str = "";
        while((len = reader.read(buf)) != -1) {
            str += new String(buf, 0, len);
        }
        return str;

        //方式三:避免出现乱码
//        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//        byte[] buffer = new byte[10];
//        int len;
//        while((len = fis.read(buffer)) != -1) {
//            baos.write(buffer, 0, len);
//        }
//        return baos.toString();

    }
}

13.11、NIO.2中Path、Paths、Files类的使用








转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/341142.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号