黑马程序员 File对象,结合流对象一起使用,弥补流对象的不足,properties类的重要应用(毕向东)

来源:互联网 发布:供给侧改革成效数据 编辑:程序博客网 时间:2024/04/28 19:28
File类常见方法:
1,创建。
boolean createNewFile():在指定位置创建文件,如果该文件已经存在,则不创建,返回false。
和输出流不一样,输出流对象一建立创建文件。而且文件已经存在,会覆盖。


boolean mkdir():创建文件夹。
boolean mkdirs():创建多级文件夹。
2,删除。
boolean delete():删除失败返回false。如果文件正在被使用,则删除不了返回falsel。
void deleteOnExit();告诉虚拟机,在程序退出时删除指定文件。




3,判断。
boolean exists() :文件是否存在.把文件封装成对象的好处,判断文件是否存在。
isFile():
isDirectory();带点和扩展名也可以是文件夹或目录
isHidden();
isAbsolute();


4,获取信息。
getName():
getPath():封装的什么路径,就得到什么路径
getParent():


getAbsolutePath() 
long lastModified() 

long length() 

class FileDemo {public static void main(String[] args) throws IOException{method_5();}public static void method_5(){File f1 = new File("c:\\Test.java");File f2 = new File("d:\\hahah.java");sop("rename:"+f2.renameTo(f1));}public static void method_4(){File f = new File("file.txt");sop("path:"+f.getPath());sop("abspath:"+f.getAbsolutePath());sop("parent:"+f.getParent());//该方法返回的是绝对路径中的父目录。如果获取的是相对路径,返回null。//如果相对路径中有上一层目录那么该目录就是返回结果。}public static void method_3()throws IOException{File f = new File("d:\\java1223\\day20\\file2.txt");//f.createNewFile();//f.mkdir();//记住在判断文件对象是否是文件或者目的时,必须要先判断该文件对象封装的内容是否存在。//通过exists判断。sop("dir:"+f.isDirectory());sop("file:"+f.isFile());sop(f.isAbsolute());}public static void method_2(){File f = new File("file.txt");//sop("exists:"+f.exists());//sop("execute:"+f.canExecute());//创建文件夹File dir = new File("abc\\kkk\\a\\a\\dd\\ee\\qq\\aaa");sop("mkdir:"+dir.mkdirs());}public static void method_1()throws IOException{File f = new File("file.txt");//sop("create:"+f.createNewFile());//sop("delete:"+f.delete());}//创建File对象public static void consMethod(){//将a.txt封装成file对象。可以将已有的和为出现的文件或者文件夹封装成对象。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);File f4 = new File("c:"+File.separator+"abc"+File.separator+"zzz"+File.separator+"a.txt");}public static void sop(Object obj){System.out.println(obj);}}

2.列出文件目录,列出指定文件下的指定扩展名的文件

import java.io.*;class  FileDemo2{public static void main(String[] args) {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:\\java1223\\day18");String[] arr = dir.list(new FilenameFilter(){public boolean accept(File dir,String name){///System.out.println("dir:"+dir+"....name::"+name);/*if(name.endsWith(".bmp"))return true;elsereturn false;*/return name.endsWith(".bmp");}});System.out.println("len:"+arr.length);for(String name : arr){System.out.println(name);}}public static void listDemo(){File f = new File("c:\\abc.txt");String[] names = f.list();//调用list方法的file对象必须是封装了一个目录。该目录还必须存在。for(String name : names){System.out.println(name);}}public static void listRootsDemo(){File[] files = File.listRoots();for(File f : files){System.out.println(f);}}}


3.列出指定目录下文件或者文件夹,包含子目录中的内容。也就是列出指定目录下所有内容。

/*列出指定目录下文件或者文件夹,包含子目录中的内容。也就是列出指定目录下所有内容。因为目录中还有目录,只要使用同一个列出目录功能的函数完成即可。在列出过程中出现的还是目录的话,还可以再次调用本功能。也就是函数自身调用自身。这种表现形式,或者编程手法,称为递归。递归要注意:1,限定条件。2,要注意递归的次数。尽量避免内存溢出。*/import java.io.*;class FileDemo3 {public static void main(String[] args) {File dir = new File("d:\\testdir");//showDir(dir,0);//toBin(6);//int n = getSum(8000);//System.out.println("n="+n);System.out.println(dir.delete());}public static String getLevel(int level){StringBuilder sb = new StringBuilder();sb.append("|--");for(int x=0; x<level; x++){//sb.append("|--");sb.insert(0,"|  ");}return sb.toString();}public static void showDir(File dir,int level){System.out.println(getLevel(level)+dir.getName());level++;File[] files = dir.listFiles();for(int x=0; x<files.length; x++){if(files[x].isDirectory())showDir(files[x],level);elseSystem.out.println(getLevel(level)+files[x]);}}public static int getSum(int n){if(n==1)return 1;return n+getSum(n-1);}public static void toBin(int num){if(num>0){toBin(num/2);System.out.println(num%2);}}public static void method(){method();}}



4.练习
将一个指定目录下的java文件的绝对路径,存储到一个文本文件中。
建立一个java文件列表文件。


思路:
1,对指定的目录进行递归。
2,获取递归过程所以的java文件的路径。
3,将这些路径存储到集合中。
4,将集合中的数据写入到一个文件中。

import java.io.*;import java.util.*;class  JavaFileList{public static void main(String[] args) throws IOException{File dir = new File("d:\\java1223");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;}}}}


5.Properties是hashtable的子类。
也就是说它具备map集合的特点。而且它里面存储的键值对都是字符串。


是集合中和IO技术相结合的集合容器。


该对象的特点:可以用于键值对形式的配置文件。


那么在加载数据时,需要数据有固定格式:键=值。


import java.io.*;import java.util.*;class PropertiesDemo {public static void main(String[] args) throws IOException{//method_1();loadDemo();}public static void loadDemo()throws IOException{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");//haha是注释,以#开头//System.out.println(prop);prop.list(System.out);fos.close();fis.close();}//演示,如何将流中的数据存储到集合中。//想要将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]);prop.setProperty(arr[0],arr[1]);}bufr.close();System.out.println(prop);}//设置和获取元素。public static void setAndGet(){Properties prop = new Properties();prop.setProperty("zhangsan","30");prop.setProperty("lisi","39");//System.out.println(prop);String value = prop.getProperty("lisi");//System.out.println(value);prop.setProperty("lisi",89+"");Set<String> names = prop.stringPropertyNames();for(String s : names){System.out.println(s+":"+prop.getProperty(s));}}}




info.txt内容:


#haha

#Wed Jan 19 15:13:48 CST 2011
zhangsan=30
lisi=57
wangwu=39


6.练习:限制程序运行次数。当运行次数到达5次时,给出,请您注册的提示。并不再让该程序执行。奋斗

/*用于记录应用程序运行次数。如果使用次数已到,那么给出注册提示。很容易想到的是:计数器。可是该计数器定义在程序中,随着程序的运行而在内存中存在,并进行自增。可是随着该应用程序的退出,该计数器也在内存中消失了。下一次在启动该程序,又重新开始从0计数。这样不是我们想要的。程序即使结束,该计数器的值也存在。下次程序启动在会先加载该计数器的值并加1后在重新存储起来。所以要建立一个配置文件。用于记录该软件的使用次数。该配置文件使用键值对的形式。这样便于阅读数据,并操作数据。键值对数据是map集合。数据是以文件形式存储,使用io技术。那么map+io -->properties.配置文件可以实现应用程序数据的共享。*/import java.io.*;import java.util.*;class  RunCount{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);//prop中有数据啦int count = 0;String value = prop.getProperty("time");//拿到time属性的值,为字符串类型,第一次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();}}/*name=zhangsanage=20<persons><person id="001"><name>zhagnsan</name><age>30</age><address>bj</address></person><person><name</person></persons>*/

7.作为了解

/*删除一个带内容的目录。删除原理:在window中,删除目录从里面往外删除的。既然是从里往外删除。就需要用到递归。*/import java.io.*;class  RemoveDir{public static void main(String[] args) {File dir = new File("d:\\testdir");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]);elseSystem.out.println(files[x].toString()+":-file-:"+files[x].delete());}System.out.println(dir+"::dir::"+dir.delete());}}


1 0