黑马程序员_File类

来源:互联网 发布:2016年拐卖儿童数据 编辑:程序博客网 时间:2024/04/29 20:54

----------- android培训java培训、java学习型技术博客、期待与您交流! ------------

File类

 1.用来将文件或者文件夹封装成对象
 2.方便对文件与文件夹的属性信息进行操作。
 3.File对象可以作为参数传递给流给流的构造函数
 4.了解File类中的常用方法


 流只能操作数据,而要想操作封装的文件或文件夹对象,则只能用File类对象


一:File类的基本操作
 1.将a.txt封装成对象,可以将已有的和未出现的文件或文件夹封装成对象
File f1=new File("a.txt");
File f2=new File("c:\\abc","b.txt"); //这一句与下面的两句等级
File d=new File("c:\\abc");
        File f3=new File(d,"c.txt");
        sop("f1:"+f1);   //打印的是文件的路径,封装的是相对的,绝对的,打印的就是
        sop("f2:"+f2);   //相对的,绝对的
        sop("f3:"+f3);
 2.File f4=new File("c:"+File.separator+"abc\\zzz\\a.txt");
   separator():与系统有关的默认分隔符,用字符串表示,在任何系统下都能选用默认的分隔符
   即它有跨平台性,调用它则用选用的格式替换\


二:File类常见方法:
 1.创建:
   boolean createNewFile():在指定路径创建文件,如该文件已存在,则不创建,返回false
   和输出流不一样,输出流对象创建文件。而且文件已经存在,则覆盖


   boolean mkdir():创建文件夹
   boolean mkdirs():创建多级文件夹
 2.删除:
   boolean delete():删除失败返回false。如果文件正在被使用,则删除不了返回false
   void deleteOnExit():在推出时删除指定文件。一般针对临时文件,如网管的setting文件
 3.判断
   boolean exists():判断文件是否存在
   isFile();
   isDirectory();
   isHidden():判断文件是否为隐藏,java中在用某个文件前先要判断是否为隐藏,java只对
   非隐藏的文件进行操作
   isAbsolution():判断是否是所封装的文件的路径是否为绝对路径


   只要文件能执行,可以用Runtime将机子上所有可执行的文件调出来
 4.获取信息
   getName();
   getParent():返回的是绝对路径中的父目录,如果获取的是相对路径,返回的为空,
               如果相对路径中有上一层目录,该目录就是返回的结果
   getPath():封装的是什么路径,返回的就是什么路径
   getAbsolutePath();无论封装的路径是相对的还是绝对的,都返回绝对路径
   lastModified():返回此路径名指示的文件的最后修改时间
   Length(); 
   eg:
   public static void main(String[] args)  throws IOException
{
  //Method_1();
        //Method_2();
   //Method_3();
        //Method_4();
Method_5();
}
public static void Method_3() throws IOException
{
File f=new File("D:\\Documents\\EditPlus\\JAVA高级视频_IO输入与输出\\file.txt");
sop("path:"+f.getPath());
sop("abspath:"+f.getAbsolutePath());
sop("parent:"+f.getParent());
}
public static void Method_4() throws IOException
{
File f=new File("D:\\Documents\\EditPlus\\JAVA高级视频_IO输入与输出\\file.txt");
sop("path:"+f.getPath());
sop("abspath:"+f.getAbsolutePath());
sop("parent:"+f.getParent());
}
public static void Method_5() throws IOException
{
File f1=new File("SystemInfo.java");
        File f2=new File("c:\\haha.java");
sop("rename:"+f2.renameTo(f1));
}
public static void Method_1() throws IOException
{
File f=new File("file.txt");
//f.deleteOnExit();
sop("create:"+f.createNewFile());
        //sop("create:"+f.delete());
}
public static void Method_2() throws IOException
{
   //File f=new File("FileDemo.java");
File f=new File("file.txt");
//sop("exists:"+f.exists());
//sop("create:"+f.canExecute());
//创建文件夹
File dir=new File("abc\\kk\\dd\\ff");
//sop("mkdir:"+dir.mkdir());
sop("mkdir:"+dir.mkdirs());
}
public static void sop(Object obj)
{
System.out.println(obj);
}
    
        list():遍历指定目录下的文件或文件夹的名称,返回的是一个字符串数组,里面放该目录下的所有文          件和文件夹名,调用list方法的文件对象必须是封装了一个目录,该目录还必须存在 
        listFiles():遍历指定的目录,返回的是一个由文件名组成的对象数组。
        eg:
        public static void main(String[] args) 
{
  //listRootsDemo(); 
  //listDemo();
 File dir=new File("c:\\");
 File [] files=dir.listFiles();
 for(File f: files)
 {
             System.out.println(f.getName()+":"+f.length());
 }   
}
public static void listDemo_2()
{
  File dir=new File("D:\\Documents\\EditPlus\\JAVA高级视频_IO输入与输出");
  String [] arr=dir.list(new FilenameFilter()
  {
     public boolean accept(File dir,String name)
     {
 //System.out.println("dir:"+dir+"name:"+name);
 return name.endsWith(".java");
 //return true;
     }
});
//当accept的返回值为真或假时,打印的结果不一样,说明list方法依赖佚名类的
//accept方法来决定是否遍历该目录下的所有文件


System.out.println("len:"+arr.length);
for(String name: arr)
{
            System.out.println(name);
}
}
public static void listDemo()
{
   File f=new File("c:\\");
            String [] names=f.list();
   for(String name:names)
   {
System.out.println(name);
   }
}
public static void listRootsDemo()
{
   File [] files=File.listRoots();
   {
for(File f : files)
{
  System.out.println(f.length());
}
   }
}


三:递归:因为目录中还有目录,只要使用同一个目录功能的函数完成即可
    在列出过程中出现的还是目录的话,还可以再次调用本功能,也就是自己调用自己,
    这种表现形式或编程手法称为递归
    递归要注意:
    1.限定条件
    2.要注意递归的次数。尽量避免内存的溢出
    列出指定目录下文件或者文件夹,包含子目录中的内容,也就是指定目录下的所有内容
    eg1:
    File dir=new File("D:\\C语言资料\\实验题源代码");
    public static void showDir(File dir)
{
   File [] files=dir.listFiles();
   for(int x=0;x<files.length;x++)
   {
     if(files[x].isDirectory())
        showDir(files[x]);
     else
System.out.println(files[x]);
   }
         }
     eg2:
     int n=getSum(80000);
     public static int getSum(int n)
{
   if(n==1)
      return 1;
   return n+getSum(n-1);
}


四:删除原理:
   在Windows中,删除是从里往外删除的,java程序中要用到递归
   eg:删除文件一个带内容的目录
   File dir=new File("D:\\java");
   removeDir(dir);
   public static void removeDir(File dir)
   {
       File [] files=dir.listFiles();
       for(int x=0;x<files.length;x++)
       {
 if(files[x].isDirectory())
     removeDir(files[x]);
 else
     System.out.println(files[x].toString()+":-files-:"+files[x].delete());
       }
 System.out.println(dir+":dir:"+dir.delete());
   }


五:将一个指定目录下的java文件的绝对路径,存储到一个文本文件中,建立一个java文件列表
    
 思路:
 1.对指定的目录进行遍历
 2.获取递归过程所有的java文件的路径
 3.将这些文件存储到集合中
 4.将集合中的文件写入到一个文件中
 eg:
 public static void main(String[] args) throws IOException
 {
File dir=new File("D:\\java");
List<File> list=new ArrayList<File>();
        fileToList(dir,list);
//System.out.println(list.size());
        File file=new File(dir,"javalist.txt");
writeToFile(list,file.toString());
 }
 public static void fileToList(File dir,List<File> list)
 {
File [] files=dir.listFiles();
for(File file:files)
{
if(file.isDirectory())
   fileToList(file,list);
else
{
   if(file.getName().endsWith(".java"));
list.add(file);
}
}
 }
 public static void writeToFile(List<File>list,String javaListFile)  throws IOException
 {
BufferedWriter bufw=null;
try
{
bufw=new BufferedWriter(new FileWriter(javaListFile));
for(File f:list)
{
String path=f.getAbsolutePath();
bufw.write(path);
bufw.newLine();
bufw.flush();
}
}
catch (IOException e)
{
throw e;
}
finally
{
try
{
   if(bufw!=null)
     bufw.close();
}
catch(IOException e)
{
   throw e;
}
}
 }


六:properties类
 1.Properties是hashtable的子类
   也就是说它具备map集合的特点,而且它里面存储的键值对都是字符串
 2.除了能加载流中的数据,还能将它集合中的数据存储到指定的文件中
 3.properties读取的文件中的数据,凡是前面带了#号的都表示注释信息,不会被Properties加载,
   而且properties加载的值都是键值对
 4.是集合和IO技术相结合的集合容器
   该对象的特点,可以用于键值对形式的配置文件
 5.split():围绕此模式的匹配拆分给定输入序列
 6.setProperty():调用 Hashtable 的方法 put,返回值是 Hashtable 调用 put 的结果。
 eg1:将加载的文件中某属性的键值修改后存回到原文件
     Properties prop=new Properties();
FileInputStream fis=new FileInputStream("info.txt");
//将流中的数据加载进集合
prop.load(fis);
prop.setProperty("wangwu","39");
FileOutputStream fos=new FileOutputStream("info.txt");
prop.store(fos,"haha");
//System.out.println(prop);
prop.list(System.out);
fos.close();
fis.close();
 eg2:将流中的数据存储到集合中及将info.txt中的键值数据存到集合中进行操作
     思路:
     1.用一个流和info.txt文件关联
     2.读取一行数据,将该行的数据用 “=”进行切割
     3.等号左边作为键,右边作为值,存入到Properties集合中即可 
     public static void method_1() throws IOException 
{
BufferedReader bufr=new BufferedReader(new FileReader("info.txt"));
String line=null;
Properties prop=new Properties();
while((line=bufr.readLine())!=null)
{
String [] arr=line.split("=");
//System.out.println(arr[0),arr[1]+"..."+arr[9];
   prop.setProperty(arr[0],arr[1]);
}
bufr.close();
System.out.println(prop);
}


七:编写一个程序:用于记录应用程序运行次数,如果使用次数已到,那么给出注册提示
    要求:程序即使结束,该计数器的值也存在下次程序再启动会先加载该计数器的值并加1后
          再重新保存起来
    方法:建立一个配置文件用于记录该软件的使用次数,配置文件使用键值对的形式,以便于阅读数据,              并操作数据,键值对数据是map集合,数据是以文件存储,使用IO技术
          配置文件可以实现应用程序数据的共享
    eg:
    public static void main(String[] args) throws IOException
    {
Properties prop=new Properties();
File file=new File("count.ini");
if(!file.exists())
file.createNewFile();
FileInputStream fis=new FileInputStream(file);
prop.load(fis);
int count=0;
String value=prop.getProperty("time");
if(value!=null)
{
    count=Integer.parseInt(value);
    if(count>=5)
    {
System.out.println("你好,使用次数已到,请续费!");
  return;
    }
}
count++;
prop.setProperty("time", count+"");
FileOutputStream fos=new FileOutputStream(file);
prop.store(fos,"");
fos.close();
fis.close();

    }


----------------------- android培训java培训、java学习型技术博客、期待与您交流! ----------------------

原创粉丝点击