欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

字符流与文件复制

程序员文章站 2024-03-04 16:37:17
...

字符流

解析:
1.一个字符一个字符的读
2.只能用来操作字符(不能写图片 音频 视频)
Windows系统 一个中文字符 占2字节
默认使用GBK的编码表(简体中文)

FileWirter
构造方法(绑定写入的路径)

2.测试字符流输入的内容

public class text {
    public static void main(String[] args) throws IOException {
        //创建字符流路径指向haha.txt
        FileWriter f = new FileWriter("/Users/lanou/Desktop/test/haha.txt");
        f.write(100);//往haha.txt中写入一个数字
        f.flush();//文件刷新

        char[] c = {'a','b','c','d','a','q'};
        f.write(c);//往文件中写入一个字符数组
        f.flush();//刷新目标文件

        f.write(c,1,3);//往目标文件中输入数组位置角标1到3的字符数组
        f.flush();//刷新

        f.write("写个格式\n格式单位");//往目标文件输入一个字符串
        f.flush();//刷新

        f.write("大小多少",1,2);//往目标文件输入字符串的截取对象
        f.flush();//刷新

        f.close();//关闭写入程序
    }
}

注意:关闭程序一定要写不然写入无法停止

4.循环读取

public class Demo05 {
    public static void main(String[] args) throws IOException{
        FileReader fr = new FileReader("/Users/lanou/Desktop/test/haha.txt");
        // 循环读取(两种)
        int len;
//      while((len = fr.read()) != -1) {
//          System.out.println((char)len);
//      }
        char[] ch = new char[1024];
        while((len = fr.read(ch))!= -1) {
            System.out.println(new String(ch, 0, len));
        }
//      int read = fr.read();
//      System.out.println(read);
//      fr.close();
    }
}
注意:
写的时候可以直接写入字符串
 读的时候不能 因为 字符串很难界定到哪里结束 不太容易判断一个字符串

3.复制文件的时间(使用模板设计模式)

public class Demo11 {

}
abstract class Fun{
    public static long getFun1() {
        System.out.println("系统计时已开始");
        long start = System.currentTimeMillis();
        return start;
    }
    public abstract void copy(File file1,File file2);
    public static long getFun2() {
        System.out.println("系统计时已结束");
        long stop = System.currentTimeMillis();
        return stop;
    }

}
class Fun1 extends Fun{
    @Override
    public void copy(File file1,File file2) {
        // TODO Auto-generated method stub
        try {
            FileWriter fw = new FileWriter(file2);
            FileReader fr = new FileReader(file1);

            int len = 0;
            char[] cs = new char[1024];
            while((len = fr.read(cs)) != -1) {
                fw.write(cs);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

4.字符流的两种读取文件方式(单个字节读/字符数组读)

public class Demo10 {
    public static void main(String[] args) {
        readByCha(new File("/Users/lanou/Desktop/test/znb.txt"));
    }

    //字符流的读取文件方式(字符数组)
    public static void readByCha(File file) {
        FileReader fr = null;
        try {
            fr = new FileReader(file);
            int len = 0;
            char[] c = new char[1024];
            while((len = fr.read(c))!= -1) {
                System.out.println(new String(c, 0, len));
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            throw new RuntimeException("打开失败");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            throw new RuntimeException("读取失败");
        }finally {
            if(fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    System.out.println("文件关闭失败");
                }
            }
        }

    }
    //字符流的读取文件方式单字符
    public static void readByChar(File file) {
        FileReader fr = null;
        try {
            fr = new FileReader(file);
            int length = 0;
            while((length = fr.read())!= -1) {
                System.out.println((char)length);
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            throw new RuntimeException("连接文件失败");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            throw new RuntimeException("读取文件失败");
        }finally {
            if(fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    throw new RuntimeException("关闭异常");
                }
            }
        }

    }

    //字节流的两种读取文件方式(字节数组读)
    @SuppressWarnings("resource")
    public static void readFromFileByByt(File file) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            int len = 0;
            byte[] bs = new byte[1024];
            while((len = fis.read(bs)) != -1) {
                System.out.println(new String(bs,0,len));
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            throw new RuntimeException("文件不存在");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            throw new RuntimeException("文件读取失败");
        }finally {
            if(fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    System.out.println("文件关闭失败");
                }
            }
        }

    }

    //字节流的两种读取文件方式(单个字节读)
    @SuppressWarnings("resource")
    public void readFromFileByByte(File file) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            int len = 0;
            while((len = fis.read()) != -1) {
                System.out.println((char)len);
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            throw new RuntimeException("文件不存在");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            throw new RuntimeException("文件读取失败");
        }finally {
            if(file != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    System.out.println("文件关闭失败");
                }
            }
        }

    }
}

6.将一个文件夹下的所有txt文件 复制 到另一个文件夹下 并且把txt改成java

public class Demo09 {
    public static void main(String[] args) throws IOException {
        File file1 = new File("/Users/lanou/Desktop/test");
        File file2 = new File("/Users/lanou/Desktop/test3");
        copyDirToAnotherFile(file1, file2);
    }

    //将一个文件夹下的所有txt文件 复制 到另一个文件夹下 并且把txt改成java
    public static void copyDirToAnotherFile(File src,File dest) throws IOException {
        File[] files = src.listFiles(new MyFileFilter());
        for (File subFile : files) {
            if(subFile.isFile()) {
                String name = subFile.getName();
                int lastIndexOf = name.lastIndexOf(".");
                String substring = name.substring(0, lastIndexOf);

                String string = substring + ".java";
                File file = new File(dest,string);
                file.createNewFile();
            }else {
                copyDirToAnotherFile(subFile, dest);
            }
        }
    }
}
class MyFileFilter implements FileFilter{

    @Override
    public boolean accept(File pathname) {
        // TODO Auto-generated method stub
        if(pathname.isDirectory()) {
            return true;
        }
        return pathname.getName().endsWith("txt");
    }

}

2.转换流

  OutputStreamWriter(字符流转向字节流)
  作用:不同编码格式写入
  需要使用到 FileOutputStream 类

  OutputStream 字节流父类
  Writer 字符流父类

  InputStreamReader
  作用:可以读取不同编码格式的文件
  需要使用到FileInputStream
public class Demo07 {
    public static void main(String[] args) throws IOException {
        //getUTF8();
        //getGBK();
        //readUTF8();
        readGBK();
    }

    // 利用转换流读文件 默认UTF-8
    public static void readUTF8() throws IOException {
        FileInputStream fls = new FileInputStream("/Users/lanou/Desktop/test/utf8.txt");
        InputStreamReader isr = new InputStreamReader(fls);
        char[] c = new char[1024];
        int len;
        while((len = isr.read(c)) != -1) {
            System.out.println(new String(c, 0, len));
        }
        isr.close();
    }

    // 利用转换流读文件 使用GBK
    public static  void readGBK() throws IOException {
        FileInputStream fis = new FileInputStream("/Users/lanou/Desktop/test/gbk.txt");
        InputStreamReader isr = new InputStreamReader(fis, "GBK");
        char[] c = new char[1024];
        int len;
        while((len = isr.read(c)) != -1) {
            System.out.println(new String(c, 0, len));
        }
        isr.close();
    }



    // 利用转换流写文件OutputStreamWriter   默认UTF-8写的
    public static void getUTF8() throws IOException{ 
        FileOutputStream fos = new FileOutputStream("/Users/lanou/Desktop/test/utf8.txt");
        // 创建转换流 字符流转向字节流
        OutputStreamWriter osw = new OutputStreamWriter(fos);

        // 写文件
        osw.write("窗前");
        // 关闭资源(只关闭外层流就可以了)
        osw.close();
    }

    // 使用转换流使用GBK编码写入文件
    public static void getGBK() throws IOException {
        FileOutputStream fos = new FileOutputStream("/Users/lanou/Desktop/test/gbk.txt");
        // 构建转换流 传入编码格式(编码格式字符串 忽略大小写)
        OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK");
        osw.write("明月");
        osw.close();
    }
}

字符流与文件复制