zoukankan      html  css  js  c++  java
  • java12 File类

    1)File类
    2)IO流的原理及概念
    3)IO流的分类
    4)IO流类的体系
    5)字节流和字符流
    6)处理流
    7)文件拷贝
    8)处理流
    9)文件拷贝
    10)文件分割与合并
    
    File:文件和目录路径名的抽象表示形式,一个File对象可以代表一个文件或目录,但不是完全对应的。建立File对象不会对文件系统产生影响。
    
    /**
     * 两个常量
     * 1、路径分隔符  ;
     * 2、名称分隔符 (windows)  /(linux 等不是windows的)
     */
    public class Demo01 {
        public static void main(String[] args) {
            System.out.println(File.pathSeparator);//
            System.out.println(File.separator);//
            //路径表示形式
            String path ="E:\xp\test\2.jpg";//E:xp	est2.jpg,有特殊含义所以要转义,
            path="E:"+File.separator+"xp"+File.separator+"test"+File.separator+"2.jpg";//E:xp	est2.jpg,这样分隔符可以做到跨平台,用于路径的动态生成。
            //推荐方式
            path="E:/xp/test/2.jpg";
        }
    }
    
    
    
    绝对路径:windows里面d:或者D:,非windows里面/开头。
    相对路径:
    
    import java.io.File;
    /**
     * 相对路径与绝对路径构造 File对象
     * 1、相对路径
        File(String parent, String child)  ==>File("E:/xp/test","2.jpg")
        File(File parent, String child)     ==> File(new File("E:/xp/test"),"2.jpg")
        2、绝对路径
        File(String name);
     */
    public class Demo02 {
        public static void main(String[] args) {
            String parentPath ="E:/xp/test";
            String name ="2.jpg";
            //相对路径,相对于父路径E:/xp/test,
            File src =new File(parentPath,name);
            src =new File(new File(parentPath),name);//src为E:xp	est2.jpg,
            //输出
            System.out.println(src.getName());//2.jpg
            System.out.println(src.getPath());//E:xp	est2.jpg,这里并不会检查文件是否存在在,
            //绝对路径
            src =new File("E:/xp/test/2.jpg");//E:xp	est2.jpg
            System.out.println(src.getName());//2.jpg
            System.out.println(src.getPath());//E:xp	est2.jpg
            //没有盘符: 以 user.dir(当前工程路径)构建
            src =new File("test.txt");//src为test.txt
            src =new File(".");//src为.,点表示当前路径。
            System.out.println(src.getName());//.
            System.out.println(src.getPath());//.
            System.out.println(src.getAbsolutePath());//E:workspace2014625143-168.
        }
    }
    
    
    
    /**
     * 常用方法:
    1、文件名
    getName() 文件名、路径名
    getPath()路径名
    getAbsoluteFile() 绝对路径所对应的File对象
    getAbsolutePath() 绝对路径名
    getParent() 父目录 ,相对路径的父目录,可能为null 如. 删除本身后的结果
    2、判断信息
    exists()
    canWrite()
    canRead()
    isFile()
    isDirectory()
    isAbsolute():消除平台差异,ie以盘符开头,其他以/开头
    3、长度 字节数  不能读取文件夹的长度
    length()
    4、创建、删除
    createNewFile() 不存在创建新文件,存在则创建失败返回false。
    delete() 删除文件
    static createTempFile(前缀3个字节长,后缀默认.temp) 默认路径为当前工程目录,
    staticcreateTempFile(前缀3个字节长,后缀默认.temp,目录)
    deleteOnExit() 退出虚拟机删除,常用于删除临时文件
     */
    public class Demo03 {
        public static void main(String[] args) {
            test1();
            test2();
            try {
                test3();
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("文件操作失败");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //创建删除文件
        public static void test3() throws IOException, InterruptedException{
            //createNewFile() 不存在创建新文件
            //String path="E:/xp/test/con"; //con系统关键字
            String path="E:/xp/test/200.jpg";
            //String path="E:/xp/test/1.jpg";
            File src =new File(path);//src为E:xp	est200.jpg
            if(!src.exists()){
                boolean flag =src.createNewFile();//xp/test目录要存在。
                System.out.println(flag?"成功":"失败");
            }
            //删除文件
            boolean flag =src.delete();
            System.out.println(flag?"成功":"失败");
            //static createTempFile(前缀3个字节长,后缀默认.temp) 默认临时空间
            //static createTempFile(前缀3个字节长,后缀默认.temp,目录)
            File temp= File.createTempFile("tes", ".temp",new File("e:/xp/test"));//tes3855104819688816342.temp        
            Thread.sleep(10000);        
            temp.deleteOnExit(); //退出即删除
        }
        //2、判断信息
        //3、长度 length()
        public static void test2(){
            String path0 ="2.txt";
            String path="E:/xp/test/200.jpg";
            String path1="E:/xp/test";
            File src =new File(path1);//src为E:xp	est200.jpg
            //是否存在
            System.out.println("文件是否存在:"+src.exists());
            //是否可读 写 canWrite() canRead()
            System.out.println("文件是否可写"+src.canWrite());
            System.out.println("============");
            //isFile()
            //isDirectory()
            if(src.isFile()){
                System.out.println("文件");
            }else if(src.isDirectory()){            
                System.out.println("文件夹");
            }else{
                System.out.println("文件不存在");
            }
            System.out.println("是否为绝对路径"+src.isAbsolute());
            System.out.println("长度为:"+src.length());//字节数
        }
        //1、名称
        public static void test1(){
            File src0 =new File("E:/xp/test/2.jpg");///scr为E:xp	est2.jpg
            //建立联系
            File src =new File("2.txt");//src为2.txt
            System.out.println(src.getName()); //返回名称,2.txt
            System.out.println(src.getPath()); //如果是绝对路径,返回完整路径,否则相对路径
            System.out.println(src.getAbsolutePath());//返回绝对路径,E:workspace2014625143-1682.txt
            System.out.println(src.getParent());//返回上一级目录,如果是相对,返回null
        }
    }
    
    
    
    import java.io.File;
    import java.io.FilenameFilter;
    /**
     * 5、操作目录
    mkdir() 创建目录,必须确保 父目录存在,如果不存在,创建失败
    mkdirs() 创建目录,如果父目录链不存在一同创建
    list() 文件|目录 名字符串形式
    listFiles()
    static listRoots() 根路径
     */
    public class Demo04 {
        public static void main(String[] args) {
            test1();
            String path ="E:/xp/test/";
            File src =new File(path); //文件夹,src为E:xp	est
            if(src.isDirectory()){ //E:/xp/test/必须存在并且为目录
                String[] subNames =src.list();//src下面的所有子文件和子文件夹,[a.txt, b.png, c.pdf, d.xml, parent]
                for(String temp:subNames){
                    System.out.println(temp);//a.txt,b.png,c.pdf,d.xml,parent
                }
                File[] subFiles =src.listFiles();//[E:xp	esta.txt, E:xp	est.png, E:xp	estc.pdf, E:xp	estd.xml, E:xp	este.java, E:xp	estparent]
                for(File temp:subFiles){
                    System.out.println(temp.getAbsolutePath());
                    /*E:xp	esta.txt
                    E:xp	est.png
                    E:xp	estc.pdf
                    E:xp	estd.xml
                    E:xp	estparent*/
                }
                for(File temp:subFiles){
                    System.out.println(temp.getPath());
                    /*E:xp	esta.txt
                    E:xp	est.png
                    E:xp	estc.pdf
                    E:xp	estd.xml
                    E:xp	estparent*/
                }
                //命令设计模式,里面是一个过滤器,必须重写accept方法,
                subFiles =src.listFiles(new FilenameFilter(){
                    //FilenameFilter是一个接口,接口是不能new的,只能创建匿名对象。这是接口的声明,只不过声明和实例化在一起。
                    /*public
                    interface FilenameFilter {
                        /**
                         * Tests if a specified file should be included in a file list.
                         *
                         * @param   dir    the directory in which the file was found.
                         * @param   name   the name of the file.
                         * @return  <code>true</code> if and only if the name should be
                         * included in the file list; <code>false</code> otherwise.
                         *//*
                        boolean accept(File dir, String name);
                    }*/
                    @Override
                    /**
                     * dir 代表src,dir为E:xp	est,在一个一个的过滤的时候name分别为a.txt,b.png,c.pdf,d.xml,e.java,parent(src下子文件和子文件夹的名称)
                     */
                    public boolean accept(File dir, String name) {//把src一个一个的过滤,把满足条件的获取出来,
                        System.out.println(dir.getAbsolutePath());
                        return  new File(dir,name).isFile()&&name.endsWith(".java");//new File(dir,name)根据路径和文件名创建文件。
                    }
                });
                for(File temp:subFiles){//subFiles为[E:xp	este.java]
                    System.out.println(temp.getAbsolutePath());//E:xp	este.java
                }
            }
        }
        public static void test1(){
            String path ="E:/xp/test/parent/p/test.jpg";//最后创建的是test.jpg这个文件夹。
            File src =new File(path);
            src.mkdir();
            src.mkdirs();//目录不存在则一同创建文件夹
        }
    }
    
    
    /**
     * 输出子孙级目录|文件的名称(绝对路径)
     * 1、listFiles()
     * 2、递归
     * static listRoots() 根路径
     */
    public class Demo05 {
        public static void main(String[] args) {
            String path ="E:/xp/test";
            File parent =new File(path);
            printName(parent);
            File[] roots =File.listRoots();
            System.out.println(Arrays.toString(roots));
            for(File temp:roots){
                //printName(temp);
            }
        }
        /**
         * 输出路径
         */
        public static void printName(File src){
            if(null==src || !src.exists()){
                return ;
            }
            System.out.println(src.getAbsolutePath());
            if(src.isDirectory()){ //文件夹
                for(File sub:src.listFiles()){
                    printName(sub);
                }
            }
        }
    }
    IO流:
    1.源头与目的地,程序与文件|数组|网络连接|数据库
    2.IO流的分类
        1)以程序为中心,进来叫输入流,出去叫输出流。    2)按数据分为:字节流(二进制,可以处理一切文件,包括纯文本、doc、音频、视频。字节流是对程序来说的,程序能看懂的),字符流(只能处理文本文件,全部为可见字符,对人类来说的,人类能看懂的)。    3)按功能分为:节点流(包裹源头),处理流(增强功能,提高性能)
    3.字符流与字节流与文件
        InputStream和OutputStream都是抽象的,    1)字节流:分为输入流[抽象类为InputStream]和输出流[抽象类为OutputStream](相对程序来说)。FileInputStream和FileOutputStream。
        2)字符流:    输入流[抽象类为Reader]和输出流[抽象类为Writer]。FileReader和FileWriter。
        
    一、读取文件(四个步骤)
    1)建立联系:File对象 是程序为中心是源头
    2)选择流:文件输入流  接口InputStream  实现类FileInputStream 
    3)操作:byte[] car = new byte[1024]+read+读取大小,输出
    4)释放资源
    
    
    /**
     * 文件的读取
     * 1、建立联系   File对象
        2、选择流     文件输入流  InputStream FileInputStream
        3、操作  : byte[] car =new byte[1024];  +read+读取大小
                  输出
        4、释放资源 :关闭
     */
    public class Demo01 {
        public static void main(String[] args) {
            //1、建立联系,File对象,文件要存在。
            File src =new File("e:/xp/test/a.txt");
            //2、选择流
            InputStream is =null; //提升作用域
            try {
                is =new FileInputStream(src);//FileInputStream为InputStream的子类(只要程序与外界存在联系就有异常),
                //3、操作,不断读取,按字节读每次读1024个字节,相当于一个缓冲数组
                byte[] car =new byte[1024];
                int len =0; //接收 实际读取大小,len表示每次实际装入到car数组中的个数,只有左后一个小于1024,在下次就为-1,
                //循环读取
                StringBuilder sb =new StringBuilder();
                while(-1!=(len=is.read(car))){
                    //输出  字节数组转成字符串
                    String info =new String(car,0,len);
                    sb.append(info);
                }
                System.out.println(sb.toString());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                System.out.println("文件不存在");
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("读取文件失败");
            }finally{
                try {
                    //4、释放资源内存区域,断开引用
                    if (null != is) {
                        is.close();
                    }
                } catch (Exception e2) {
                    System.out.println("关闭文件输入流失败");
                }
            }
        }
    
    }
    
    
    二、写出文件(四个步骤)
    1)建立联系:File对象 以程序为中心是目的地
    2)选择流:文件输出流 接口OutputStream  实现类FileOutputStream 
    3)操作:byte[] car = new byte[1024]+read+读取大小,输出
    4)释放资源
    /**
     * 写出文件
    1、建立联系   File对象  目的地
    2、选择流     文件输出流  OutputStream FileOutputStream
    3、操作  :  write() +flush
    4、释放资源 :关闭
     */
    public class Demo02 {
        public static void main(String[] args) {
            //1、建立联系,File对象,目的地
            File dest =new File("e:/xp/test/test.txt");
            //2、选择流   文件输出流  OutputStream FileOutputStream
            OutputStream os =null;
            //以追加形式 写出文件 必须为true,否则为覆盖文件
            try {
                os =new FileOutputStream(dest,true);
                //3、操作
                String str="过头如果 
    ";
                //字符串转字节数组
                byte[] data =str.getBytes();
    //            /[98, 106, 115, 120, 116, 32, 105, 115, 32, 118, 101, 114, 121, 32, 103, 111, 111, 100, 32, 13, 10]
                os.write(data,0,data.length);
                os.flush(); //强制刷新出去,因为相当于一个管道。管道没满就不出去,所以要手动出去。
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                System.out.println("文件未找到");
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("文件写出失败");
            }finally{
                //4、回收内存,断开引用,释放资源 :关闭
                try {
                    if (null != os) {
                        os.close();
                    }
                } catch (Exception e2) {
                    System.out.println("关闭输出流失败");
                }
            }
        }
    }
    
    
    
    
    文件的拷贝:
    文件从源地到目的地,中间通过程序。先把文件从源地Read到程序,然后从程序write到目的地,读一点写一点。
    四个步骤:
    1、建立联系   File对象   源头 目的地
    2、选择流     
         文件输入流  接口InputStream  实现类FileInputStream
         文件输出流  接口OutputStream 实现类FileOutputStream
    3、操作:拷贝
         byte[] flush =new byte[1024]; 
         int len =0;
         while(-1!=(len=输入流.read(flush))){  
            输出流.write(flush,0,len)
         }
         输出流.flush
    4、释放资源 :关闭 两个流
    
    
    
    文件的拷贝:
    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;
    
    /**
     1、建立联系   File对象   源头 目的地
    2、选择流     
         文件输入流  InputStream FileInputStream
          文件输出流  OutputStream FileOutputStream
    3、操作  :  拷贝
         byte[] flush =new byte[1024]; 
         int len =0;
          while(-1!=(len=输入流.read(flush))){  
             输出流.write(flush,0,len)
          }
                 输出流.flush
    4、释放资源 :关闭 两个流
     */
    public class CopyFileDemo {
        public static void main(String[] args) {
            String src ="E:/xp/test/1.txt";//源文件必须存在,并且是文件不是文件夹,文件夹不能用流读取。
            String dest="e:/xp/test/2.txt";//目的文件可以不存在
            try {
                copyFile(src,dest);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                System.out.println("文件不存在");
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("拷贝文件失败|关闭流失败");
            }
        }
        /**
         * 文件的拷贝
         * @param  源文件路径
         * @param  目录文件路径
         * @throws FileNotFoundException,IOException
         */
            public static void copyFile(String srcPath,String destPath) throws FileNotFoundException,IOException {
                //1、建立联系 源(存在且为文件) +目的地(文件可以不存在)  
                File src =new File(srcPath);//src为E:xp	est1.txt,内容为a-z
                File dest =new File(destPath);//dest为e:xp	est2.txt
                if(!src.isFile()){ //不是文件或者为null
                    System.out.println("只能拷贝文件");
                    throw new IOException("只能拷贝文件");//throw之后方法就出去了,后面就不用加return
                }
                //2、选择流
                InputStream is =new FileInputStream(src);//如果src是文件夹,这里就会出错,因为文件夹是没有流来读取的,
                OutputStream os =new FileOutputStream(dest);
                //3、文件拷贝   循环+读取+写出
                byte[] flush =new byte[10];//每次读10个字节到flush数组里面去
                int len =0;
                //读取
                //len=is.read(flush);
                //len=20,flush为长度为20的数组
                while(-1!=(len=is.read(flush))){
                    //写出
                    os.write(flush, 0, len);//len为实际的长度                //每次循环,从源读取10到flush,然后从flush写入到目的地,再次读取10个到flush然后写入到目的地,读一点写一点。
                    //flush=[97, 98, 99, 100, 101, 102, 103, 104, 105, 106],len=10,2.txt内容为abcdefghij
                    //flush=[107, 108, 109, 110, 111, 112, 113, 114, 115, 116],len=10,2.txt内容为abcdefghijklmnopqrst
                    //flush=[117, 118, 119, 120, 121, 122, 113, 114, 115, 116],len=6,2.txt内容为abcdefghijklmnopqrstuvwxyz
                }
                os.flush(); //强制刷出            //关闭流,后打开先关闭,os和is不可能为空,所以关闭之前不用对os和is进行判空,
                os.close();
                is.close();
            }
    }
    
    
    
    
    文件夹的拷贝:
    1.递归查找子孙文件|文件夹
    2.如果是文件,赋值(FileIO流)即可,如果是文件夹创建即可。
          A
        / | 
    1.txt aa b.png
          |
        2.txt
    
    
    
        /**
     * 文件夹的拷贝
     * 1、文件 赋值  copyFile
     * 2、文件 创建 mkdirs()
     * 3、递归查找子孙级
     */
    public class CopyDir {
        public static void main(String[] args) {
            //源目录
            String srcPath="E:/xp/test/a";//目录结构如下
            /*    a
                / | 
            1.txt aa b.png
                  |
                2.txt    */
                
            //目标目录
            String destPath="E:/xp/test/b";//把a文件夹赋值到b文件夹的下面
            //FileUtil.copyDir(srcPath,destPath);
            copyDir(srcPath,destPath);
        }
        
        /**
         * 拷贝文件夹
         * @param src 源路径
         * @param dest 目标路径
         */
        public static void copyDir(String srcPath,String destPath){
            File src=new File(srcPath);
            File dest =new File(destPath);
            copyDir(src,dest);        
        }
        
        /**
         * 拷贝文件夹
         * @param src 源File对象
         * @param dest 目标File对象
         */
        public static void copyDir(File src,File dest){//src为E:xp	esta,dest为E:xp	est
            if(src.isDirectory()){ //文件夹
                System.out.println(src.getName());//a
                try {
                    dest =new File(dest,src.getName());//dest为E:xp	esta,在dest下创建一个文件夹名字为src.getName()
                    new File(dest,"a2");
                } catch (Exception e) {
                    e.printStackTrace();
                }            
            }        
            try {
                copyDirDetail(src,dest);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        /**
         * 拷贝文件夹细节
         * @param src
         * @param dest
         */
        public static void copyDirDetail(File src,File dest){
            if(src.isFile()){ //文件
                try {
                    FileUtil.copyFile(src, dest);
                    /*public static void copyFile(File src,File dest) throws FileNotFoundException,IOException {
                        if(! src.isFile()){ //不是文件或者为null
                            System.out.println("只能拷贝文件");
                            throw new IOException("只能拷贝文件");
                        }
                        //dest为已经存在的文件夹,不能建立于文件夹同名的文件
                        if(dest.isDirectory()){
                            System.out.println(dest.getAbsolutePath()+"不能建立于文件夹同名的文件");
                            throw new IOException(dest.getAbsolutePath()+"不能建立于文件夹同名的文件");
                        }
                        //2、选择流
                        InputStream is =new BufferedInputStream(new FileInputStream(src));
                        OutputStream os =new BufferedOutputStream(new FileOutputStream(dest));
                        //3、文件拷贝   循环+读取+写出
                        byte[] flush =new byte[1024];
                        int len =0;
                        //读取
                        while(-1!=(len=is.read(flush))){
                            //写出
                            os.write(flush, 0, len);
                        }
                        os.flush(); //强制刷出
                        //关闭流
                        os.close();
                        is.close();
                    }*/
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else if(src.isDirectory()){ //文件夹
                //确保目标文件夹存在
                dest.mkdirs();//此时b文件夹创建,并且b中创建了a文件夹,E:xp	esta->E:xp	estaaa
                File[] subFiles =src.listFiles();//[E:xp	esta1.txt, E:xp	estaaa, E:xp	esta.png]->[E:xp	estaaa2.txt]
                //获取下一级目录|文件
                for(File sub:src.listFiles()){
                    copyDirDetail(sub,new File(dest,sub.getName()));
                }
            }
        }
    }
    
    
    
    
    
    /**
     * 文件操作
     * 1、文件拷贝
     * 2、文件夹拷贝  拒绝自己拷贝给自己
     * @author Administrator
     *
     */
    public class FileUtil {
        /**
         * 拷贝文件夹
         * @param src 源路径
         * @param dest 目标路径
         * @throws IOException 
         * @throws FileNotFoundException 
         */
        public static void copyDir(String  srcPath,String destPath) throws FileNotFoundException, IOException{
            //拒绝自己拷贝给自己
            if(srcPath.equals(destPath)){
                return ;
            }
            File src=new File(srcPath);
            File dest =new File(destPath);
            copyDir(src,dest);        
        }
        
        
        
        /**
         * 拷贝文件夹
         * @param src 源File对象
         * @param dest 目标File对象
         * @throws IOException 
         * @throws FileNotFoundException 
         */
        public static void copyDir(File src,File dest) throws FileNotFoundException, IOException{
            if(src.isDirectory()){ //文件夹
                dest =new File(dest,src.getName());
                if(dest.getAbsolutePath().contains(src.getAbsolutePath())){
                    System.out.println("父目录不能拷贝到子目录中");
                    return;
                }
            }        
            copyDirDetail(src,dest);
        }
        
        /**
         * 拷贝文件夹细节
         * @param src
         * @param dest
         */
        public static void copyDirDetail(File src,File dest) throws FileNotFoundException,IOException{
            if(src.isFile()){ //文件
                try {
                    FileUtil.copyFile(src, dest);
                } catch (FileNotFoundException e) {
                    //e.printStackTrace();
                    throw e;
                } catch (IOException e) {
                    //e.printStackTrace();
                    throw e;
                }
            }else if(src.isDirectory()){ //文件夹
                //确保目标文件夹存在
                dest.mkdirs();
                //获取下一级目录|文件
                for(File sub:src.listFiles()){
                    copyDirDetail(sub,new File(dest,sub.getName()));
                }
            }
        }
        
        
        /**
         * 文件的拷贝
         * @param  源文件路径
         * @param  目录文件路径
         * @throws FileNotFoundException,IOException
         * @return 
         */
        public static void copyFile(String srcPath,String destPath) throws FileNotFoundException,IOException {
            //1、建立联系 源(存在且为文件) +目的地(文件可以不存在) 
            copyFile(new File(srcPath),new File(destPath));
        }
        /**
         * 文件的拷贝
         * @param  源文件File对象
         * @param  目录文件File对象
         * @throws FileNotFoundException,IOException
         * @return 
         */
        public static void copyFile(File src,File dest) throws FileNotFoundException,IOException {
            if(! src.isFile()){ //不是文件或者为null
                System.out.println("只能拷贝文件");
                throw new IOException("只能拷贝文件");
            }
            //dest为已经存在的文件夹,不能建立于文件夹同名的文件
            if(dest.isDirectory()){
                System.out.println(dest.getAbsolutePath()+"不能建立于文件夹同名的文件");
                throw new IOException(dest.getAbsolutePath()+"不能建立于文件夹同名的文件");
            }
            
            
            //2、选择流
            InputStream is =new BufferedInputStream(new FileInputStream(src));
            OutputStream os =new BufferedOutputStream(new FileOutputStream(dest));
            //3、文件拷贝   循环+读取+写出
            byte[] flush =new byte[1024];
            int len =0;
            //读取
            while(-1!=(len=is.read(flush))){
                //写出
                os.write(flush, 0, len);
            }
            os.flush(); //强制刷出
            
            //关闭流
            os.close();
            is.close();
        }
    }
    
    
    
    字符流:
      节点流:Reader FileReader,Writer FileWrite,
    一、纯文本读取
    1.建立联系
    2.选择流 Reader FileReader
    3.读取 char[] flush = new char[1024]
    4.关闭
    二、纯文本写出
    1.建立联系
    2.选择流 Writer FileWriter
    3.读取 write(字符数组,0,长度) + flush
           write(字符串)
           append(字符串)
    4.关闭
    
    
    
    /**
     * 纯文本读取
     */
    public class Demo01 {
        public static void main(String[] args) {
            //创建源
            File src =new File("E:/xp/test/a.txt");
            //选择流
            Reader reader =null;
            try {
                reader =new FileReader(src);
                //读取操作
                char[] flush =new char[10];
                int len =0;
                while(-1!=(len=reader.read(flush))){
                    //字符数组转成 字符串
                    String str =new String(flush,0,len);
                    System.out.println(str);
                    /*啊啊啊abcdefg
                    hijklmnopq
                    rstuvwxyz*/
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                System.out.println("源文件不存在");
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("文件读取失败");
            }finally{
                try {
                    if (null != reader) {
                        reader.close();
                    }
                } catch (Exception e2) {
                }
            }
        }
    
    }
    
    
    
    
    /**
     * 写出文件
     */
    public class Demo02 {
        public static void main(String[] args) {
            //创建源
            File dest =new File("e:/xp/test/char.txt");
            //选择流
            Writer wr =null;
            try {
                //true为追加文件,false或者不写是覆盖文件
                wr =new FileWriter(dest,false);
                //写出
                String msg ="追加.....锄禾日当午
    码农真辛苦
    一本小破书
    一读一上午";
                wr.write(msg);
                wr.append("倒萨发了看电视剧 ");
                wr.append("倒死死死死死死死死死死死萨发了看电视剧 ");
                wr.flush();//这里才写入到文件
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }catch (IOException e) {
                e.printStackTrace();
            }finally{
                try {
                    if (null != wr) {
                        wr.close();
                    }
                } catch (Exception e2) {
                }
            }
        }
    
    }
    
    
    
    /**
     * 纯文本拷贝
     */
    public class CopyFileDemo {
        public static void main(String[] args) {
            //创建源 仅限于 字符的纯文本
            File src =new File("E:/xp/test/Demo03.java");
            File dest =new File("e:/xp/test/char.txt");
            //选择流
            Reader reader =null;        
            Writer wr =null;
            try {
                reader =new FileReader(src);
                wr =new FileWriter(dest);
                //读取操作
                char[] flush =new char[1024];
                int len =0;
                while(-1!=(len=reader.read(flush))){
                    wr.write(flush, 0, len);
                }
                wr.flush();//强制刷出,即使不加flush,关闭流的时候也会刷新出去。
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                System.out.println("源文件不存在");
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("文件读取失败");
            }finally{
                try {//关闭,先打开的后关闭
                    if (null != wr) {
                        wr.close();
                    }
                } catch (Exception e2) {
                }
                try {
                    if (null != reader) {
                        reader.close();
                    }
                } catch (Exception e2) {
                }
            }
        
        }
    
    }
  • 相关阅读:
    什么是 Hystrix?它如何实现容错?
    什么是 Spring Cloud Bus?我们需要它吗?
    SpringBoot和SpringCloud的区别?
    Eureka和zookeeper都可以提供服务注册与发现的功能,请说说两个的区别?
    REST 和RPC对比?
    XML技术的作用?
    iHTML 的 form 提交之前如何验证数值文本框的内容全部为数字
    XML常用解析API有哪几种?
    XML的解析方式有哪几种?有什么区别?
    XML文档约束有哪几种?有什么区别?
  • 原文地址:https://www.cnblogs.com/yaowen/p/4833580.html
Copyright © 2011-2022 走看看