字节流

(一)输入流:

   InputStream

File file=new File("E:/test/2.txt");
            InputStream is=new FileInputStream(file);//多态,输入流文件子类
            byte[] by=new byte[1024];    //每次装载的容量
            int len=0;
            
                while(-1!=(len=is.read(by)))    //读到by字节数组里,每次读1024个字节
                {
                    //循环一次就把一次的数据给str--->字节数组转化为字符串
                    String str=new String(by,0,len);    
                    System.out.print(str);
                }

(二)输出流

    OutputStream

       File file=new File("E:/test/2.txt");
            /*追加形式为true*/
            OutputStream os=new FileOutputStream(file,true);
            String str="dfjkdfmckdi idi jdk kd
";
            /*字符串转为字节数组*/
            byte[] data=str.getBytes();  //输出数据是字节数组,转化为字节
            os.write(data);
            os.flush();

 (三)复制文件

    CopyFile

File src=new File("E:/test/1.jpg");
        File dest=new File("E:/test/10.jpg");
        InputStream is=new FileInputStream(src);
        OutputStream os=new FileOutputStream(dest);
        byte[] data=new byte[1024];
        int len=0;
        while((len=is.read(data))!=-1)    //读取数据返回长度
        {
            os.write(data, 0, len);
        }
        os.close();
        is.close();

(四)复制文件与文档

  CopyDirFile

  

package ByteStreamDemo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class CopyDirDemo2 {

    public static void main(String[] args) throws IOException {
        File src = new File("E:/test/abc");
        File dest = new File("E:/test/dir/aa");
        CopyDir(src, dest);
    }

    public static void CopyDir(File src, File dest) throws IOException {
        /**
         * 1.传两个路径过来
         * 2.如果源文件是目录,目标文件就创建完整路径
         * 3.循环取出源文件下的子文件。(子文件源文件File对象,新建一个目标文件
         * 路径加名字)[abc/abcd] [abc/1.txt] [10.jpg]------>
         * 目标File对象[..aa/abcd][..aa/1.txt][..aa/10.jpg]
         */
        if (src.isDirectory()) {
            dest.mkdirs();
            for (File sub : src.listFiles()) {
                /*sub.getName() 取最后一级文件或文件夹*/
                CopyDir(sub, new File(dest, sub.getName()));//
            }

        } else if (src.isFile()) {
            CopyFile(src, dest);
        }

    }

    public static void CopyFile(File src, File dest) throws IOException {

        InputStream is = new FileInputStream(src);
        OutputStream os = new FileOutputStream(dest);
        byte[] data = new byte[1024];
        int len = 0;
        while ((len = is.read(data)) != -1) // 读取数据返回长度
        {
            os.write(data, 0, len);
        }
        os.close();
        is.close();
    }

}
原文地址:https://www.cnblogs.com/yugeng/p/8060418.html