io流复制文件

假如在D盘根目录有个 hello.txt 文件,要放到C盘 hello/hello.txt 里面(流的操作,可以类比程序对数据库的操作,就是对电脑文件的“增删改查”)

public void chuLi() throws Exception {
        
        //取到要操作的文件
        File file1 = new File("D:/hello.txt");
        FileInputStream fis = new FileInputStream(file1);
        InputStreamReader isr = new InputStreamReader(fis,"gbk");
        BufferedReader br = new BufferedReader(isr);
        StringBuffer sb = new StringBuffer();
        String con = "";
     //int con2 = 0;
while((con=br.readLine())!=null) {//使用 BufferedReader 可以一行一行读取,使用 String ,和 null 比较
     //while((con2=isr.read())!=-1) {//不使用缓冲流,只能一个字节一个字节读取,使用 int ,和 -1 比较 sb.append(con
+" ");
       //sb.append((char)con2);//将 int 转成 char 字节 }
byte[] bs = sb.toString().getBytes(); //创建目标路径 File file2 = new File("C:/hello"); if(!file2.exists()) { file2.mkdirs(); } File file3 = new File(file2.getPath()+"/hello2.txt"); if(file3.exists()) { file3.createNewFile(); } FileOutputStream fos = new FileOutputStream(file3); fos.write(bs); fos.flush(); fos.close(); br.close(); isr.close(); System.out.println("走完了,请查看"); } public static void main(String[] args) throws Exception { Test test = new Test(); test.chuLi(); }

为了效率输入流使用 BufferedReader 缓冲流,可以实现一行一行读取数据,但读取速度快的同时,会带来字符编码问题,需要注意!

使用输出流后,要 flush 一下,最后一次关闭流


原文地址:https://www.cnblogs.com/xuehuashanghe/p/10741985.html