zoukankan      html  css  js  c++  java
  • 详谈JAVA中的file类与IO流

    File类
    位于java.io包
    构造方法:
    File(String parent, String child)
    new file("d:\","a.txt");

    File(String pathname)
    new file("d:\a.txt");

    File(File parent, String child)
    File f = new File("d:\");
    File f1=new File(f,"a.txt");

    常用方法:
    1.获取
    1)文件名
    String getName()
    2)文件路径
    String getAbsolutePath()
    3)大小
    long length()
    3)最后修改时间
    long lastModified()

    1 File file=new File("d:\aa.txt");
    2 System.out.println(file.getName());
    3 System.out.println(file.getAbsolutePath());
    4 System.out.println(file.lastModified());
    5 
    6 long l=file.lastModified();
    7 Date date=new Date(l);
    8 System.out.println(date.toString());
    9 System.out.println(file.length());

    2.创建与删除
    1)创建文件
    boolean createNewFile()
    2)创建文件夹(目录)
    boolean mkdir() 单层
    boolean mkdirs() 多层
    3)删除文件和目录
    boolean delete()

    1 File f=new File("d:\b.txt");
    2 boolean b=f.createNewFile();
    3 System.out.println(b);
    4 f.delete();
    1 File f1=new File("d:\ch1027");
    2 f1.mkdir();//建立单层目录
    3 File f2=new File("d:\ch1028\ch1029\ch1030");
    4 f2.mkdirs();//建立多层目录
    5 
    6 f2.delete();//删除的是ch1030文件夹

    3.判断
    boolean isDirectory() 测试此抽象路径名表示的文件是否是一个目录。
    boolean isFile() 测试此抽象路径名表示的文件是否是一个标准文件。
    boolean isHidden() 测试此抽象路径名指定的文件是否是一个隐藏文件。 

    1 File f1=new File("d:\ch1027");
    2 System.out.println(f1.isDirectory());
    3 System.out.println(f1.isFile());
    4 
    5 File f= new File("d:\bb.txt");
    6 boolean b = f.createNewFile();
    7 System.out.println(f.isHidden());//false,默认不隐藏

    4.重命名
    boolean renameTo(File dest)
    1)同目录 ---- 改名
    2)不同目录 ----- 相当于剪切

    1 File f= new File("f:\bb6.txt");
    2 File f1= new File("f:\123\bb6.txt");
    3 System.out.println(f.renameTo(f1));

    5.其它
    static File[] listRoots() 列出可用的文件系统根。
    long getFreeSpace() 可用空间
    long getTotalSpace() 总容量
    String[] list() 列出目录中的文件和目录(同辈目录)

     1 //遍历出文件系统根目录
     2 File[] files = File.listRoots();
     3 for(int i=0;i<files.length;i++){
     4 System.out.println(files[i]);
     5 }
     6 
     7 //遍历目录中的文件和目录
     8 File f= new File("f:\123");
     9 String [] strs = f.list();
    10 for(int i=0;i<strs.length;i++){
    11 System.out.println(strs[i]);
    12 }

    FileFilter接口 
    文件过滤器
    例子:显示出某个目录下的,非隐藏文件
    File[] listFiles(FileFilter filter)
    参数是一个过滤器类
    详见下面程序

    //新建一个过滤非隐藏文件的过滤器,需要实现FileFilter接口
    public class FilteHidden implements FileFilter{
        public boolean accept(File file) {    
            return !file.isHidden();
        }
    }
    //新建一个文件类
    public class Filess {    
        public static void main(String[] args) {
            File file = new File("f:\123");
            File [] s = file.listFiles(new FilteHidden());//返回的是过滤后的元素
            for(int i=0;i<s.length;i++){//遍历输出每个元素的名字
                System.out.println(s[i].getName());
            }
        }
    }    

    FilenameFilter 接口
    文件名过滤器
    例子:对文件名进行过滤
    File[] listFiles(FilenameFilter filter)
    参数是一个过滤器类
    详见下面程序

     1 //创建一个文件名过滤器
     2 public class Filename implements FilenameFilter{
     3     private String endstr;
     4     public boolean accept(File dir, String name) {
     5         return name.endsWith(endstr);//返回符合输入格式的文件
     6     }
     7     Filename(String str){//传入代表文件格式的字符串
     8         endstr = str;
     9     }
    10 }
    11 
    12 public class FilenameDemo {    
    13     public static void main(String[] args) {
    14         File file= new File("f:\123");
    15         File [] files = file.listFiles(new Filename(".txt"));
    16         //遍历结果
    17         for(int i=0;i<files.length;i++){    
    18             System.out.println(files[i].getName());
    19         }    
    20     }
    21 }

    File类得到文件列表的方法
    1)列出所有文件
    File file = new File(“f:\aa”);
    File [] filearr = file.listFiles(); 表示的目录中的(文件及目录)
    String [] filearr= file.list(); 表示的目录中的(文件及目录)
    2)过滤器
    File file = new File(“f:\aa”);
    FilenameFilter接口,用于过滤文件名。
    String[] filenamearr= file.list(FilenameFilter filter)
    File[] filenamearr = file.listFiles(FilenameFilter filter)

    File file = new File(“f:\aa”);
    FileFilter接口,用于过滤文件。
    File[] filearr = file.listFiles(FileFilter filter)

    递归:自已(方法)调用自已
    例子:用递归把目录下所有的目录及文件全部显示出来

     1 public class B {
     2     public static void main(String[] args) {
     3         File file = new File("f:\123");
     4         listAllFile(file);
     5     }
     6 
     7     public static void listAllFile(File file) {
     8         File[] strs = file.listFiles();
     9         for (int i = 0; i < strs.length; i++) {
    10             // 判断strs[i]是不是目录
    11             if (strs[i].isDirectory()) {
    12                 listAllFile(strs[i]);//递归调用自己
    13                 System.out.println("目录="+strs[i].getName());
    14             } else {
    15                 System.out.println("文件名="+strs[i].getName());
    16             }
    17         }    
    18     }
    19 }       

    IO流
    IO流:输入(Input)输出(Output)流
    位置于java.io包下
    流作用:读写文件用的
    流分类
    1)按流向分(以内存为参照物):
    输入流 输出流
    2)按流的内容分:
    字节流(能读写所有文件),字符流(读取纯文本文件)
    3)按功能分:
    节点流 处理流(套在节点流上的)
    字节流,它的子类都是Stream
    字符流,它的子类是Writer Reader

    FileWriter
    文件字符输出流
    构造方法:
    注意:1)对象一创建出来就得给文件路径。
    2)如果文件存在就覆盖,不存在则创建
    3)不想覆盖,是用下面的构造方法
    FileWriter(String fileName, true)
    4)写完后要flush()
    5)写完要关闭流

     1 /**
     2 *文件字符输出流实例
     3 */
     4 public class FileWriterDemo {
     5     public static void main(String[] args) {
     6         FileWriter fw = null;
     7         try {
     8             fw = new FileWriter("d:\1.txt");
     9             fw.write("fff");
    10             fw.write("ggggg");
    11             fw.flush();
    12             int i = 10/0;//故意产生错误
    13         } catch (Exception e) {
    14             String str = e.getMessage();
    15             FileWriterDemo d = new FileWriterDemo();
    16             d.xie(str);//错误信息写入另一个文件中。
    17             e.printStackTrace(); 
    18         } finally {
    19             try {
    20                 fw.close();
    21             } catch (IOException e) {
    22                 e.printStackTrace();
    23            }
    24         }
    25     }
    26 
    27     public void xie(String str) {
    28         FileWriter fw = null;
    29         try {
    30             fw = new FileWriter("d:\2.txt", true);
    31             fw.write(str);
    32             fw.flush();
    33         } catch (IOException e) {
    34             e.printStackTrace();
    35         } finally {
    36             try {
    37                 fw.close();
    38             } catch (IOException e) {
    39                 e.printStackTrace();
    40             }
    41         }
    42     }
    43 }


    FileReader
    文件字符输入流
    代码演示:

     1 /**
     2 *文件字符输入流实例
     3 */
     4 public static void main(String[] args) {    
     5     try {
     6         FileReader fr = new FileReader("f:\1.txt");
     7         char[] buf= new char[3];
     8         int i = fr.read(buf);
     9         System.out.println(new String(buf,0,i)); 
    10         /*new String(buf,0,i) char [] buf,从char数组的第几个位置开始读,读几个*/
    11     } catch (Exception e) {
    12         e.printStackTrace();
    13     }    
    14 }



    BufferedWriter 带缓冲区的文件字符输出流
    特点:1)它是处理流,要包在节点流外面来使用
    2)提高写的效率
    3)换行newLine()
    创建对象:
    1)FileWriter fw = new FileWriter("d:\cc\cc.txt");
    BufferedWriter bw = new BufferedWriter(fw);
    2)没有捕获异常时
    BufferedWriter bw1 = new BufferedWriter(new FileWriter("d:\cc\cc3.txt"));
    bw1.write("abcbbbb");
    bw1.newLine();
    bw1.write("sssss");
    bw1.newLine();
    bw1.write("defxxx");
    bw1.flush();
    bw1.close();


    BufferedReader 带缓冲区的文件字符输入流
    特点:1)它是处理流,要包在节点流外面来使用
    2)提高读取的效率
    3)读一行readLine()
    创建对象:
    try {
      BufferedReader br= new BufferedReader(new FileReader("d:\cc\cc.txt"));
      String str=null;
      while( (str=br.readLine()) != null){
        System.out.println(str);
    } catch (Exception e) {
       e.printStackTrace();
    }


    文件的复制:

    public static void main(String[] args) {
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {    
            br = new BufferedReader(new FileReader(new File("d:\cc\cc.txt")));
            bw = new BufferedWriter(new FileWriter("d:\cc\cc5.txt"));
            String str = null;//临时接收读写的字符串
            while ((str = br.readLine()) != null) {
                bw.write(str);
                bw.newLine();
                bw.flush();
         } catch (Exception e) {
             e.printStackTrace();
         } finally {
            if (br != null) {
                try {
                   br.close();
                } catch (IOException e) {
                   e.printStackTrace();
                }
            }
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }    
    }

    FileOutputStream 文件字节输出流
    特点:1)输出的是字节
    2)不用flush()

     1 public static void main(String[] args) {
     2     FileOutputStream fos=null;
     3     try{
     4         fos = new FileOutputStream("d:\cc\cc8.txt");
     5         fos.write("abc".getBytes());
     6         //getBytes()将一个字符串转化为一个字节数组byte[]的方法
     7         fos.write(97);
     8     }catch (Exception e) {
     9         e.printStackTrace();
    10     }finally{
    11         if(fos != null){
    12              try {
    13                fos.close();
    14             } catch (IOException e) {
    15                e.printStackTrace();
    16             }
    17         }
    18     }
    19 }    

    FileInputStream 文件字节输入流
    特点:1)输入的是字节
    2)不用flush()

     1 public static void main(String[] args) {
     2     try {
     3         FileInputStream fis = new FileInputStream("d:\cc\cc8.txt");
     4         byte [] b = new byte[2];//存储临时数据
     5         int len=0;
     6         while( (len =fis.read(b)) != -1){
     7             System.out.println(new String(b,0,len));
     8         }
     9     }catch (Exception e) {
    10         e.printStackTrace();
    11     }
    12 }

    BufferedOutputStream BufferedInputStream
    带缓冲区的字节输出(输入)流
    特点:1)输出(入)的是字节
    2)是个处理流
    2)用flush()

     1 /**
     2 *字节流实现的复制功能
     3 */
     4 public static void main(String[] args) {
     5     try {
     6         BufferedInputStream bis= new BufferedInputStream( new  FileInputStream("d:\cc\cc8.txt"));
     7         BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("d:\cc\cc9.txt"));
     8         int len=0;
     9         byte [] b = new byte[1024];
    10         while( (len = bis.read(b)) !=-1 ){
    11             bos.write(b);
    12         }
    13         bos.flush();
    14     } catch (Exception e) {
    15         e.printStackTrace();
    16     }finally{//加close()方法,请参考(上面文件的复制部分)}
    17 }

    System.in
    从键盘输入得到一个流InputStream
    可以使用InputStream中的方法

     1 public static void main(String[] args) {
     2     InputStream is = System.in;
     3     int ch = 0;
     4     try {
     5         while ((ch = is.read()) != -1) {
     6         System.out.println((char) ch); //
     7        }
     8     } catch (IOException e) {
     9         e.printStackTrace();
    10     }
    11 }

    ObjectInputStream ObjectOutputStream
    对象的输入 输出流
    特点:1)写入很多数据类型
    2)写入自定义对象


    序列化:把对象存入硬盘中(属性的值)
    反序列化:把对象从硬盘中取出来(属性的值)
    注意: 1)static 修饰的属性不能存入
    2)Transient修饰的属性不能存入//transient关键字的作用:标记的成员变量不参与序列化过程
    3)对象对应的类必须要实现一个接口(空接口)Serializable接口
    4)不用flush()
    5)类中的方法不能被序列化,只能序列化属性
    程序演示:

     1 public static void main(String[] args) {
     2     try {
     3         ObjectOutputStream ous = new ObjectOutputStream(new FileOutputStream(new File("d:\cc\Animal.obj")));
     4         Animal a1= new Animal("aa",1);//Animal类是自定义的,这里未写出
     5         ous.writeObject(a1);//序列化
     6         ous.close();
     7 
     8         ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("d:\cc\Animal.obj")));
     9         Animal an=(Animal)ois.readObject();//反序列化
    10         System.out.println(an.getAge()+","+an.getName());
    11         ois.close();
    12     } catch (Exception e) {
    13         e.printStackTrace();
    14     }
    15 }
  • 相关阅读:
    将Nginx添加到windows服务中
    springboot使用redis管理session
    GIT常用命令
    阻止360、谷歌浏览器表单自动填充
    谈谈对Spring IOC的理解
    同一个Nginx服务器同一端口配置多个代理服务
    LeetCode 653. Two Sum IV
    109. Convert Sorted List to Binary Search Tree(根据有序链表构造平衡的二叉查找树)
    108. Convert Sorted Array to Binary Search Tree(从有序数组中构造平衡的BST)
    LeetCode 236. Lowest Common Ancestor of a Binary Tree(二叉树求两点LCA)
  • 原文地址:https://www.cnblogs.com/lm970585581/p/6884094.html
Copyright © 2011-2022 走看看