Java学习路程之字节流和字符流

一.字节流
1.特点:字节流可以将文字、图片、音频等文件类型转换成字节进行数据的传输。
2.分类:
输入流 OutPutStream
输出流 InPutStream
判断参照物(程序)来判断是输入流还是输出流,OutPutStream和InPutStream是所有字节流的父类
3.区分:
从程序到文件是输出流 写文件

(1). 创建字节输出流:

public class Day19 {
    public static void main(String[] args) throws IOException {
        //创建字节输出流
        FileOutputStream fos = new FileOutputStream("/Users/lanou/Desktop/test/haha.txt");
        //写入方法write(),该方法是按照ASCII码写入文件,在haha.txt文件中写入了A B.
        fos.write(65);
        fos.write(66);
        //关闭资源
        //fos.close();
        //利用字节数组写入
        byte[] b = {65,66,67};
        fos.write(b);//在haha.txt文件中写入了A B C
        //按偏移量写入字节数组
        fos.write(b, 0, 2);//在haha.txt文件中写入了A B
        //hello转成字符数组写入
        fos.write("hello".getBytes());//在haha.txt文件中写入了hello
    }
}

带异常处理的写入:

public class Demo01 {
    public static void main(String[] args)  {
        //带异常处理的写入
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream("/Users/lanou/Desktop/test/haha.txt");
            //写文件
            fos.write(65);
        } catch (FileNotFoundException e) {
            throw new RuntimeException("没有该文件");
        } catch (IOException e) {
            throw new RuntimeException("写入失败");
        }finally {
            //不能直接关闭资源,因为fos的初始值为null,当写入失败时,null不能调用方法
            if (fos != null) {
                try {
                    //不管报不报异常都要将流关闭
                    fos.close();
                } catch (Exception e2) {
                    throw new RuntimeException("关闭失败");
                }
            }
        }

    }

(2).文件的读取

 public class Day19 {
    public static void main(String[] args) throws IOException {

        FileInputStream fis = new FileInputStream("/Users/lanou/Desktop/test/haha.txt");
        //读取文件
        fis.read();//单个读取文件
        //循环读取文件
        int num= 0;
        while ((num = fis.read()) != -1) {
            System.out.println(num);//haha.txt中的内容全部读取出来
        }
        fis.close();
        //字节数组读取
        //创建数组
        byte[] b = new byte[1024];//数组长度一般填1024或1024的整数倍
        int len = 0;
        while ((len = fis.read(b)) != -1) {
            System.out.println(new String(b, 0, len));//haha.txt中的内容全部读取出来
        }
    }
}

练习1:
复制文件 ,计算两种读取文件的时间, 带异常处理
单个读取:

public static void main(String[] args) {

        //计算时间
        long start = System.currentTimeMillis();//开始时间
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream("/Users/lanou/Desktop/test/java入门.pptx");
            fos = new FileOutputStream("/Users/lanou/Desktop/test/java.pptx");
            int num = 0;
            while ((num = fis.read()) != -1) {
                //写入文件
                fos.write(num);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException("没有此文件");
        }catch (IOException e) {
            throw new RuntimeException("读写失败");
        }finally {
            if (fos != null) {
                try {
                    fos.close();//关闭资源
                } catch (Exception e2) {
                    throw new RuntimeException("关闭失败");
                }finally {
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (Exception e3) {
                            throw new RuntimeException("关闭失败");
                        }
                    }
                }
            }
        }

        long end = System.currentTimeMillis();//结束时间
        System.out.println((end - start)/1000 + "秒");
    }

字节数组读取:
public static void main(String[] args) {
        //计算时间
        long start = System.currentTimeMillis();//开始时间
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream("/Users/lanou/Desktop/test/java入门.pptx");
            fos = new FileOutputStream("/Users/lanou/Desktop/test/java.pptx");
            byte[] b = new byte[1024];
            int len = 0;
            while ((len = fis.read(b)) != -1) {
                fos.write(b, 0, len);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException("没有此文件");
        }catch (IOException e) {
            throw new RuntimeException("读写失败");
        }finally {
            if (fos != null) {
                try {
                    fos.close();//关闭资源
                } catch (Exception e2) {
                    throw new RuntimeException("关闭失败");
                }finally {
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (Exception e3) {
                            throw new RuntimeException("关闭失败");
                        }
                    }
                }
            }
        }

        long end = System.currentTimeMillis();//结束时间
        System.out.println((end - start)/1000 + "秒");
    }

练习2:
将一个文件夹 复制 到另一个文件夹下

public static void main(String[] args) throws IOException {
        //将一个文件夹 复制 到另一个文件夹下
        File src = new File("/Users/lanou/Desktop/test");
        File desc = new File("/Users/lanou/Desktop/heihei");
        copyDir(src, desc);
    }
    //将一个文件夹 复制 到另一个文件夹下
    //src 源文件   desc 目标文件
    public static void copyDir(File src,File desc) throws IOException {
        //在目标文件夹下创建文件夹
        File newFile = new File(desc, src.getName());
        File[] listFiles = newFile.listFiles();
        for (File subFile : listFiles) {
            if (subFile.isFile()) {
                //是文件进行读写
                FileInputStream fis = new FileInputStream(subFile);
                File file = new File(newFile, subFile.getName());
                //写入
                FileOutputStream fos = new FileOutputStream(file);
                byte[] b = new byte[1024];
                int len = 0;
                while ((len = fis.read(b)) != -1) {
                    fos.write(b, 0, len);
                }
            }else {
                //不是文件继续遍历
                copyDir(subFile, newFile);
            }
        }
    }

练习3:
将一个文件夹下的所有txt文件 复制到,另一个文件夹下并且保存为.java文件

public static void copyTxtFile(File src, File desc) throws IOException {
        File[] listFiles = src.listFiles(new GetTxtFile());
        for (File subFile : listFiles) {
            if (subFile.isFile()) {
                FileInputStream fis = new FileInputStream(subFile);
                //是文件,进行分割获取文件名
                String name = subFile.getName();//获取源TXT文件名
                String[] split = name.split("\\.");
                //输出流路径名
                File file = new File(desc, split[0] + ".java");
                //创建输出流
                FileOutputStream fos = new FileOutputStream(file);
                byte[] b = new byte[1024]; 
                int len = 0;
                while ((len = fis.read()) != -1) {
                    fos.write(b, 0, len);
                }
                fis.close();
                fos.close();
            }else {
                //文件夹
                copyTxtFile(subFile, desc);
            }
        }

//创建过滤器,找到是txt文件
class GetTxtFile implements FileFilter{
    public boolean accept(File pathname) {
        if (pathname.isDirectory()) {
            return true;
        }
        return pathname.getName().endsWith("txt");
    }
}

二.字符流
1.分类
Writer 写入
Reader 读取
是所有字符流的父类

public class Day19 {
    public static void main(String[] args) {
        //创建字符输出流
        FileWriter fw = new FileWriter("/Users/lanou/Desktop/test/cs.txt");
        //写入文件
        fw.write(65);//cs.txt文件写入A
        //刷新,为了内容真正写入文件
        fw.flush();
        //字符数组写入
        char[] c = {'1','2','3'};
        fw.write(c);
        fw.flush();
        //关闭前系统会自动刷新
        /字符串直接写入
        fw.write("真正的勇士,敢于直面惨淡的人生" +"\n" + "敢于正视淋漓的鲜血");
        fw.close();

        //创建输入流
        FileReader fReader = new FileReader("/Users/lanou/Desktop/test/cs.txt");
        //单个读
        int num = 0;
        while ((num = fReader.read()) != -1) {
            System.out.print((char)num);
        }
        //数组读取
        char[] c = new char[1024];
        int len = 0;
        while ((len = fReader.read(c)) != -1) {
            System.out.println(new String(c, 0, len));
        }
    }
}

练习:
复制文本文件,使用字符流,带异常处理

public class Day19 {
    public static void main(String[] args) {
        FileWriter fWriter = null;
        FileReader fReader = null;
        try {
            fReader = new FileReader("/Users/lanou/Desktop/test/cs.txt");
            fWriter = new FileWriter("/Users/lanou/Desktop/heihei/cs.txt");
            //创建字符数组
            char[] chars = new char[1024];
            int len = 0;
            //循环读取写入
            while ((len = fReader.read(chars)) != -1) {
                fWriter.write(chars, 0, len);
                fWriter.flush();//刷新
            }

        } catch (FileNotFoundException e) {
            throw new RuntimeException("没找到文件");
        }catch (Exception e) {
            throw new RuntimeException("读写失败");
        }finally {
            //关闭fReader
            if (fReader != null) {
                try {
                    fReader.close();
                } catch (Exception e2) {
                    throw new RuntimeException("关闭失败");
                }finally {
                    //关闭fWriter
                    if (fWriter != null) {
                        try {
                            fWriter.close();
                        } catch (Exception e3) {
                            throw new RuntimeException("关闭失败");
                        }
                    }
                }
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/l710820742/article/details/82694744
今日推荐