黑马程序员_File类


一.File类常见方法

1.创建

boolean createNewFile():在指定位置创建该文件,如果该文件已经存在,则不创建,返 回false;

和输出流不一样的地方:输出流对象建立后创建文件,而且文件已存在会覆盖文件;

boolean mkdir();创建文件夹

boolean makdirs();创建多级目录文件夹

2.删除

boolean delete();删除失败返回False

void deleteOnExit();在程序退出时删除文件

3.判断

boolean exists();文件是否存在

boolean canExecute():判断是否能执行

isFile();判断是否是文件

isDirectory()判断是否是目录

4.获取信息

getName();返回由此抽象路径名表示的文件或目录的名称。

getPath();获取相对路径

getAbsolutePath();获取绝对路径

getParent();返回绝对路径中的父目录,如果获取的是相对路径则返回null。例如:File f1  = new File("file.txt");则返回null,如果File f1 = new File("abc\\file.txt");则返回abc


.基本用法示例:

import java.io.*;  
class  Demo  
{  
    public static void main(String[] args) throws IOException  
    {  
        //建立一个File对象  
        File f1 = new File("file.txt");  
        //methodcre(f1);  
        //method_del(f1);  
        //method_jud(f1);  
        method_get(f1);  
    }  
    public static void methodcre(File f1) throws IOException  
    {  
        //创建文件,如果该文件已经存在,则不创建,返回false;  
        show("creat:"+f1.createNewFile());  
          
        //创建一个文件夹,如果该文件夹已经存在,则不创建,返回false;  
        File dir = new File("abc");  
        show("mkdir:"+dir.mkdir());  
          
        //创建一个多级目录文件夹,如果该多级目录文件夹已经存在,则不创建,返回false;  
        File dirs = new File("aaa\\bbb\\ccc\\ddd");  
        show("mkdirs:"+dirs.mkdirs());  
  
    }  
    public static void method_del(File f1) throws IOException  
    {  
        //删除指定文件,删除失败返回False  
        show("delete:"+f1.delete());  
        //在程序退出时删除文件,无返回值  
        f1.deleteOnExit();  
          
    }  
    public static void method_jud(File f1) throws IOException  
    {  
        //判断文件是否存在,存在则返回true  
        show(f1.exists());  
        //判断应用程序是否可以执行此抽象路径名表示的文件。  
        show(f1.canExecute());  
        //判断是否是文件  
        show(f1.isFile());  
        //判断是否是目录  
        show(f1.isDirectory());  
    }  
    public static void method_get(File f1) throws IOException  
    {  
        //返回由此抽象路径名表示的文件或目录的名称。  
        show(f1.getName());  
        //获取相对路径  
        show(f1.getPath());  
        //获取绝对路径  
        show(f1.getAbsolutePath());  
        /*返回绝对路径中的父目录,如果获取的是相对路径则返回null。 
        例如:File f1 = new File("file.txt");则返回null, 
        如果File f1 = new File("abc\\file.txt");则返回abc 
        */  
        show(f1.getParent());  
        }  
    public static void show(Object obj)  
    {  
        System.out.println(obj);  
    }  
}  

.过滤文件方法

练习:文件过滤

/* 
需求:将一个文件夹里所有的.zip格式文件名列出来 
*/  
import java.io.*;  
class Demo1   
{  
    public static void main(String[] args)   
    {  
        File files = new File("E:\\android\\java基础\\20tian");  
        //这里使用内部类实现FilenameFileter接口里面的accept功能实现文件过滤  
        String[] arr = files.list(new FilenameFilter()  
        {  
            public boolean accept(File files,String name)  
            {  
                //只要文件名字里面包含".zip",就返回true  
                return name.contains(".zip");  
            }  
        });  
        //列出符合条件的文件名  
        for (String name : arr )  
        {  
            System.out.println(name);  
        }  
    }  
} 

四.递归调用

这里要实现一个方法:列出指定目录下的所有内容

首先要实现一个可以列出目录的功能,然后在列出内容的过程中如果出现的还是目录的话,可以再次调用本功能,也就是函数自身调用自身。

注意:1.递归条件的设置

   2.要注意递归的次数,避免内存溢出

练习:列出文件夹里所有的文件名

import java.io.*;  
class Demo   
{  
    public static void main(String[] args)   
    {  
        File dir = new File("E:\\tian");  
        showdir(dir,0);  
    }  
    public static void showdir(File dir,int level)  
    {  
        System.out.println(getLevel(level)+dir);  
        level++;  
        File[] files = dir.listFiles();  
        for (int x=0;x<files.length;x++)  
        {  
            //如果该文件是目录,则再次调用showdir功能  
            if(files[x].isDirectory())  
                showdir(files[x],level);  
            else   
                System.out.println(files[x]);  
        }         
    }  
    public static String getLevel(int level)  
    {  
        StringBuilder sb = new StringBuilder();  
        for (int x=0;x<level ;x++ )  
        {  
            sb.append("|--");  
        }  
        return sb.toString();  
    }  
} 

练习:复制文件夹

import java.io.*;  
class MainClass {  
public static void main(String[] args) throws Exception  
{  
    //假设你把E盘下“aaa”这个文件夹给拷贝到E盘并命名为copyfile  
    findAndCopyPics("E:\\aaa",  
        "E:\\copyfile");  
}  
  
public static void findAndCopyPics(String fpath,String dpath) throws Exception   
{  
    File file = new File(fpath);  
    if (file.isDirectory())  
    {  
        File copyfile = new File(dpath);  
        copyfile.mkdirs();  
    }  
    File[] listFiles = file.listFiles();  
    for (File f : listFiles) {  
    if (f.isDirectory())   
    {  
        // 是文件夹就递归  
        findAndCopyPics(fpath + "\\" + f.getName(),dpath+"\\"+f.getName());  
    }   
    else   
    {  
        // 不是文件夹,即是文件就拷备  
        copyPics(fpath + "\\" + f.getName(),dpath+"\\"+f.getName());  
    }  
}  
}  
public static void copyPics(String fpath,String dpath) throws Exception   
{  
    FileInputStream fis = new FileInputStream(fpath);  
    FileOutputStream fos = new FileOutputStream(dpath);  
    byte[] b = new byte[1024];  
    int len = 0;  
    while ((len=fis.read(b))!=-1)   
    {  
        fos.write(b,0,len);  
    }  
    fis.close();  
    fos.close();  
    }  
} 


.操作配置文件

Properties可以用来操作键值对形式的配置文件,是Hashtable的子类 ,里面存储的是键值对,键值对都是字符串。

下面用代码演示它的一系列用法:

import java.io.*;  
import java.util.*;  
class Demo   
{  
    public static void main(String[] args) throws IOException  
    {  
        method_2();  
    }  
    public static void method_2() throws IOException  
    {  
        Properties prop = new Properties();  
        FileInputStream fis = new FileInputStream("info.txt");  
        //将流中的数据加载进集合  
        prop.load(fis);  
        //修改或设置数据  
        prop.setProperty("dddd","39");  
        //获得键为"bbbb"所对应的值  
        System.out.println(prop.getProperty("bbbb"));  
  
        FileOutputStream fos = new FileOutputStream("info.txt");//调用写入流  
        prop.store(fos,"aaaaaaaaaaaaaaaa");//加入注释信息“aaa”  
        System.out.println(prop);//直接打印集合  
        prop.list(System.out);//列出集合目录  
    }  
    //下面是Properties类中load方法的原理  
    public static void method_1() throws IOException  
    {  
        BufferedReader bfr = new BufferedReader(new FileReader("info.txt"));  
          
        String line = null;  
        Properties prop = new Properties();  
        while ((line=bfr.readLine())!=null)  
        {  
            String[] arr = line.split("=");  
            prop.setProperty(arr[0],arr[1]);  
        }  
        bfr.close();  
        System.out.println(prop);     
    }  
} 

练习:利用配置文件,使一个程序运行超过3 次就不能再运行

  import java.io.*;  
  import java.util.*;  
  class Demo1  
  {  
    public static void main(String[] args) throws IOException  
    {  
        File file = new File("infos.ini");  
        if (!file.exists())  
        {  
            file.createNewFile();  
        }  
        FileInputStream fis = new FileInputStream(file);  
        Properties prop = new Properties();  
        //将流中的数据加载进集合  
        prop.load(fis);  
    
        String value = prop.getProperty("time");  
        int count = 0;  
        //如果value值不为null,则判断count值是否大于3  
        if (value!=null)  
        {  
            count = Integer.parseInt(value);  
            if (count>=3)  
            {  
                System.out.println("已经运行三次了!");  
                //大于3则停止运行  
                return;  
            }  
        }  
        count++;  
        prop.setProperty("time",count+"");  
        FileOutputStream fos = new FileOutputStream(file);  
        //写入文件  
        prop.store(fos,count+"");  
        fis.close();  
        fos.close();  
    }  
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值