黑马程序员——第20天——IO输入与输出(File类,Properties,打印流,合并流,切割文件)

来源:互联网 发布:硬盘克隆软件 编辑:程序博客网 时间:2024/04/26 15:55
File类常见方法:
1,创建。
boolean createNewFile();在指定位置创建文件,如果该文件已经存在,则不创建,返回false.
和输出流不一样,输出流对象一建立创建文件。而且文件已经存在,会覆盖。
boolean mkdir():创建文件夹。
boolean mkdirs():创建多级文件夹。
2,删除.
boolean delete():删除失败返回false。
void deleteOnExit():在程序退出时删除指定文件。
3,判断
boolean exists():文件是否存在
isFile():
isDirectory():
isHidden():
isAbsolute();


4,获取信息。
getName():
getPath():
getParent():


getAbsolutePath():
long lastModified():返回时间,最后一次修改的时间

long length()

import java.io.*;class  FileDemo{public static void main(String[] args) {consMethod();}public static void method_5()throws IOException{File f1 = new File();File f2 = new File();}public static void method_4()throws IOException{File f = new File("file.txt");sop("path:"+f.getPath());sop("abspath:"+getAbsolutePath());sop("parent:"+f.getParent());//该方法返回的是绝对路径中的父目录。如果获取的是相对路径,返回空。//如果相对路径中有上一层目录,那么该目录就是返回结果。}public static void method_3()throws IOException{File f = new File("file.txt");//f.createNewFile();//f.mkdir();//记住在判断文件是否是文件或者目录时,必须要先判断该文件对象封装的内容是否存在。//通过exists判断。sop("dir:"+f.isDirectory);}public static void method_2()throws IOException{File f = new File("");sop("exists:"+f.exists());//sop("execute:"+f.canExecute());//创建文件夹File fir = new File("abc\\kk\\aa\\ss\\dd");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+"d.txt");//跨平台的分隔符,separator}public static void sop(Object obj){System.out.println(obj);}}

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());}listRootsDemo();listDemo();}public static void listDemo2(){File dir = new File("e:\\java2014\\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;else return 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 = FIlle.listRoots();for(File f : files){System.out.println(f);}}}

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

/*<strong>删除一个带内容的目录。</strong>删除原理:在windows中,删除目录从里往外删除的。既然是从里往外删除。就需要用到递归。*/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(file[x]);//elseSystem.out.println(files[x].toString()+"::"+files[x].delete());}System.out.println(dir+"::dir::"+dir.delete());}}
<strong>练习:</strong>
/*练习将一个指定目录下的java文件的绝对路径,存储到一个文本文件中。建立一个java文件列表文件。思路:1,对指定的目录进行递归。2,获取递归过程中所有的java文件的路径。3,将这些路径存储到集合中。4,将集合中的数据写入到一个文件中。*/import java.util.*;import java.io.*;class JavaFileList {public static void main(String[] args) throws IOException{File dir = new File("e:\\java2014");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().endWith(".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.writ(path);bufw.newLine();bufw.flush();}}catch (IOException e){throw e;}finally{try{if(bufw!=null)bufw.close();}catch (IOException e){throw e;}}}}
<strong>Properties</strong>
/*Properties是hashtable的子类。也就是说它具备map集合的特点。而且它里面存储的键值对都是字符串。是集合中和IO技术相结合的集合容器。该对象的特点:可以用于键值对形式的配置文件。那么在加载数据时,需要数据有固定格式:键=值*/import java.io.*;import java.util.*;class PropertiesDemo {public static void main(String[] args) throws IOException{//setAndGet();//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");//修改内存中的结果,怎么改到流中,存到硬盘?storeFileOutputStream fos = new FileOutputStream("info.txt");prop.store(fos,"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 = buf.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 Peoperties();prop.setProperties("zhangsan","30");prop.setProperties("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));}}}

练习:
记录程序运行次数

/*用于记录应用程序运行次数。如果使用次数已到,那么给出注册提示。很容易想到的是:计数器。可是该计数器定义在程序中,随着程序的运行而在内存中存在,并进行自增。可是随着该应用的退出,该计数器也在内存中消失了。下一次在启动该程序,又重新开始从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();prop.load(fis);int count = 0;String value = prop.getProperty("time");if(value!=null){count = Integer.parseInt(value);if(count>=5){System.out.println("您好,使用次数已到,拿钱");rerun;}}count++;prop.setProperty("time",count+"");FileOutputStream fos = new FileOutputStream(file);prop.store(fos,"");fos.close();fis.close();}}//xml封装形式比prop方便//dom4j  工具更方便



/*<strong>打印流:</strong>该流提供了打印方法,可以将各种数据类型的数据都原样打印。字节打印流:PrintStream构造函数可以接收的参数类型:1,file对象。File2,字符串路径。String3,字节输出流。OutputStream字符打印流:PrintWriter构造函数可以接收的参数类型:1,file对象。File2,字符串路径。String3,字节输出流。OutputStream4,字符输出流。Writer*/class  PrintStreamDemo{public static void main(String[] args) {BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));PrintWriter out =new PrintWriter(System.out,true);//PrintWriter out =new PrintWriter(new FileWriter("a.txt").true);提高效率再加BufferedString line = null;while((line=bufr.line())!=null){if("over".equals(line))break;out.println(line.toUpperCase());//out.flush();}out.close();bufr.close();}}

<strong>Sequence合并流</strong>
import java.io.*;class SequenceDemo {public static void main(String[] args) {Vector<FileInputStream> v = new Vector<FileInputStream>();v.add(new FileInputStream("c:\\1.txt"));v.add(new FileInputStream("c:\\2.txt"));v.add(new FileInputStream("c:\\3.txt"));Enumeration<FileInputStream> en = v.elements();FileOutputStream fos = new FileOutputStream(en);SequenceInputStream sis = new SequenceInputStream("c:\\4.txt");byte[] buf = new byte[1024];int len = 0;while((len=sis.read(buf))!=-1){fos.write(buf,0,len);}fos.close();sis.close();}}
切割文件
import java.io.*;import java.tuil.*;class  SplitFile{public static void main(String[] args) {splitFile();merge();}public static void merge()throws IOException{ArraryList<FileInputStream> al = new ArraryList<FileInputStream>();for (int x=1;x<=3 ;X++ ){al.add(new FileInputStream("c:\\splitfile\\"+x+".part"));}Iterator<FileInputStream> it = al.iterator();Enumeration<FileInputStream> en = new Enumeration<FileInputStream>(){public boolean hasMoreElements(){return it.hasNext();}public FileInputStream nextElement(){return it.hasNext();}};SequenceInputStream sis = new SequenceInputStream(en);FileOutputStream fos new FileOutputStream("c:\\splitFile\\0.bmp");byte[] buf = new byte[1024];int len = 0;while((len=sis.read(buf))!=-1){fos.write(buf,0,len);}fos.close();sis.close();}public static void splitFile(){FileInputStream fis = new FileInputStream("c:\\1.bmp");FileOutputStream fos = null;byte[] buf = new byte[1024*1024];int len = 0;int count = 1;while((len=fis.read(buf))!=-1){fos = new FileOutputStream("c:\\splitfile\\"+(count+++)+".part");fos.write(buf,0,len);fos.close();}}}


0 0
原创粉丝点击