黑马程序员—IO流(下)File类、管道流、PrintStream、序列流、propertis

来源:互联网 发布:淘宝定时开售怎么设置 编辑:程序博客网 时间:2024/06/05 20:40

----------android培训、java培训、期待与您交流!----------

1.File

1:创建。

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

                                                       和输出流不一样,输出流对象一建立创建文件。而且文件已经存在,

会覆盖。

 

        boolean   mkdir():创建文件夹。

        boolean   mkdirs():创建多级文件夹。

2:删除。

        boolean    delete():删除失败返回false。如果文件正在被使用,则删除不了返回falsel

        void   delete   OnExit();在程序退出时删除指定文件。

 

 

3:判断。

        boolean       exists() :判断文件是否存在.

        isFile():判断是否是一个标准文件

        isDirectory();判断是否是一个目录(文件夹)

        isHidden();判断是否是一个隐藏文件

        isAbsolute();判断是否是绝对路径名

 

4:获取信息。

        getName():获取文件名

        getPath():获取文件的相对路径

        getParent():获取文件所在绝对路径的父目录,如果获取的是相对路径,返回null

 

        getAbsolutePath()获取文件的绝对路径

        longlastModified()返回此抽象路径名表示的文件最后一次修改的时间

        longlength()返回由此抽象路径名表示的文件长度


/*  练习  将一个指定目录下的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());                              Filefile = new File(dir,"javalist.txt");                      writeToFile(list,file.toString());                }            public static void fileToList(File dir,List<File> list)            {                      File[] files = dir.listFiles();                          for(Filefile : 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)throwsIOException            {                      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)                      {                               throwe;                      }                      finally                      {                               try                               {                                        if(bufw!=null)                                                  bufw.close();                               }                               catch(IOException e)                               {                                        throwe;                               }                      }            }   }

2.管道流

PipedInputStream和PipedOutputStream

输入输出可以直接进行连接,通过结合线程使用

import java.io.*;       class Read implements Runnable   {            private PipedInputStream in;            Read(PipedInputStream in)            {                      this.in= in;            }            public void run()            {                      try                      {                               byte[] buf = new byte[1024];                                   System.out.println("读取前。。没有数据阻塞");                               int len = in.read(buf);                               System.out.println("读到数据。。阻塞结束");                                           String s= new String(buf,0,len);                                   System.out.println(s);                                   in.close();                          }                      catch(IOException e)                      {                               thrownew RuntimeException("管道读取流失败");                      }            }   }       class Write implements Runnable   {            private PipedOutputStream out;            Write(PipedOutputStreamout)            {                      this.out= out;            }            public void run()            {                      try                      {                               System.out.println("开始写入数据,等待6秒后。");                               Thread.sleep(6000);                               out.write("pipedlai la".getBytes());                               out.close();                      }                      catch(Exception e)                      {                               thrownew RuntimeException("管道输出流失败");                      }            }   }       class PipedStreamDemo   {            public static void main(String[] args) throws IOException            {                          PipedInputStream in = new PipedInputStream();                      PipedOutputStream out = new PipedOutputStream();                      in.connect(out);                          Read r = new Read(in);                      Write w = new Write(out);                      newThread(r).start();                      newThread(w).start();                    }   }


3.PrintStream

打印流:

该流提供了打印方法,可以将各种数据类型的数据都原样打印。

字节打印流:PrintStream

构造函数可以接收的参数类型:

1file对象。File

2,字符串路径。String

3,字节输出流。OutputStream

 字符打印流:PrintWriter

构造函数可以接收的参数类型:

1file对象。File

2,字符串路径。String

3,字节输出流。OutputStream

4,字符输出流,Writer

import java.io.*;       class PrintStreamDemo   {            publicstatic void main(String[] args) throws IOException            {                      BufferedReader bufr =                               new BufferedReader(new InputStreamReader(System.in));                          PrintWriter out = new PrintWriter(new FileWriter("a.txt"),true);                          String line = null;                          while((line=bufr.readLine())!=null)                      {                               if("over".equals(line))                                        break;                               out.println(line.toUpperCase());                               //out.flush();                      }                          out.close();                      bufr.close();                }          }

4.序列流:

序列流可以将多个流,合并成一个流.可用于文件的合并

 import java.io.*;   import java.util.*;       class SplitFile   {            public static void main(String[] args) throws IOException            {                      //splitFile();                      merge();            }                //合并文件            public static void merge()throws IOException            {                      ArrayList<FileInputStream> al = new ArrayList<FileInputStream>();                          for(int x=1; x<=3; x++)                      {                               al.add(newFileInputStream("c:\\splitfiles\\"+x+".part"));                      }                        Enumeration<FileInputStream> en=Collections.enumeration(al);SequenceInputStream sis = new SequenceInputStream(en);                              FileOutputStream fos = new FileOutputStream("c:\\splitfiles\\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()throws IOException            {                      FileInputStream fis =  newFileInputStream("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 = newFileOutputStream("c:\\splitfiles\\"+(count++)+".part");                               fos.write(buf,0,len);                               fos.close();                      }                                           fis.close();                                 }   }


5.Propertis

Properties类表示了一个持久的属性集。Properties可保存在流中或从流中加载。

属性列表中每个键及其对应值都是一个字符串。

PropertiesHashtable的子类,具备map集合的特点,里面程序的键值对都是字符串。
也是集合中和IO技术相结合的集合容器,特点是可以用于键值对形式的配置文件。
在加载数据是时,需要数据有固定格式:key=value

方法
getProperty(String key)
用指定的键在此属性列表中搜索属性。 
String getProperty(String key, String defaultValue)
用指定的键在属性列表中搜索属性。 
void list(PrintStream out)
将属性列表输出到指定的输出流。 
void list(PrintWriter out)
将属性列表输出到指定的输出流。 
void load(InputStream inStream)
从输入流中读取属性列表(键和元素对)。 
void load(Reader reader)
按简单的面向行的格式从输入字符流中读取属性列表(键和元素对)。 
Object setProperty(String key, String value)
调用 Hashtable的方法 put 
stringPropertyNames()
返回此属性列表中的键集,其中该键及其对应值是字符串,如果在主属性列表中未找到同名的键,则还包括默认属性列表中不同的键。

void store(OutputStream out,String comments) 以适合使用 load(InputStream) 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。

void store(Writer writer,String comments)
          以适合使用 load(Reader) 方法的格式,将此 Properties 表中的属性列表(键和元素对)写入输出字符。

 import java.io.*;   import java.util.*;   class RunCountDemo{       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);                            //从文件输入流fis中加载数据到属性集prop。           int count = 1;                             //定义计数器           String value = prop.getProperty("num");    //获取属性集中键为nun的值           if(Integer.parseInt(value)<0){               System.out.println("企图修改计数器是无效的!");               return;            }           else if(value==null){                           //如果此值==null,表示第一次使用。               System.out.println("试用剩余"+(5-count)+"次");               return ;           }           else{                   count = Integer.parseInt(value);       //记录运行次数count                if(count>=5){                           //如果运行超过了5次                   System.out.println("试用结束,请先注册!"); //发出提示                   return ;                                    //结束程序               }               System.out.println("试用剩余"+(5-count)+"次");               count++;            }                                             //计数器自增           prop.setProperty("num",count+"");          //保存到属性集中           FileOutputStream fos = new FileOutputStream(file);//创建写入流fos           prop.store(fos,"");                        //将属性集中的数据保存到fos中           fos.close();                               //关闭写入流。           fis.close();                               //关闭读取流。       }   } 




原创粉丝点击