黑马程序员_IO流(3)

来源:互联网 发布:json字符串转对象 编辑:程序博客网 时间:2024/05/16 08:53

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


/ *

 【Properties】:

Properties是HashTable的子类,因此具备了Map集合的特性。

它存储的键值对都是字符串。

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

 

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

 

因此在加载数据时,要求数据有固定格式:键=值。

* // *

import java.util.*;

import java.io.*;

class  PropertiesDemo

{

       public static voidmain(String[] args) throws IOException

       {

              loadMethod();

       }

       public static voidloadMethod() throws IOException{

            

              BufferedReaderbufr = new BufferedReader(new FileReader("info.txt"));

              Properties prop= new Properties();

              //1.6版本以后出现的用法,将流中的数据加载进集合

             //prop.load(bufr);

              prop.load(newFileInputStream("info.txt"));

            

             prop.setProperty("Rachel","27");

 

              FileOutputStreamfos = new FileOutputStream("info.txt");

             prop.store(fos,"Rachel");

             System.out.println(prop);

              bufr.close();

              fos.close();

       }

       //将info.txt文件中的键值对存储到集合中进行操作

       public static voidmethod_1() throws IOException{

              BufferedReader bufr = newBufferedReader(new FileReader("info.txt"));

              Properties prop= new Properties();

            

              String line =null;

              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);

       }

            }

}

* // *

【记录应用程序的使用次数】

如果次数已到,给出注册提示。

使用计数器。

但是计数器定义在程序中,程序运行时加载进内存,而程序退出时随之消失。

下次启动程序时,又是一个重新初始化的计数器。这达不到想要的结果。

因此

需要建立一个配置文件,记录软件的使用次数。

并且,该配置应使用键值对形式,便于阅读和操作数据(配置文件中不止计数)。

键值对数据使用Map集合,数据以文件形式存储,即io技术

因此,Map+IO--->Properties                         

配置文件可以实现应用程序数据的共享。

* // *

import java.io.*;

import java.util.*;

class  PropertiesDemo

{

       public static voidmain(String[] args) throws IOException{

              Properties prop= new Properties();

              File file = newFile("count.ini");

              if(!file.exists())

                    file.createNewFile();

 

              FileInputStreamfis = 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("Times Limit .Please pay again");

              }

              count++;

             prop.setProperty("time",count+"");

              FileOutputStreamfos = new FileOutputStream(file);

             prop.store(fos,"");

            

              fis.close();

              fos.close();

       }

     

}

* // *

--------------------------------------------------------------------------

打印流:【PrintStream和PrintWriter】

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

【字节打印流】:  PrintStream

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

1.file对象,Flie

2.字符串路径,String

3.字节输出流,OutputStream

【字符打印流】:  PrintWriter

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

1.file对象,Flie

2.字符串路径,String

3.字节输出流,OutputStream

4.字符输出流,Writer

* // *

import java.io.*;

class PrintStreamDemo

{

       public static voidmain(String[] args) throws IOException{

              BufferedReaderbufr =

                     newBufferedReader(new InputStreamReader(System.in));

            

              //加true参数后,println可以自动刷新

              //PrintWriterout = new PrintWriter(System.out,true);

              //PrintWriterout = new PrintWriter("print.txt");

              PrintWriter out= new PrintWriter(new FileWriter("print.txt"),true);

              String line = null;

 

              while ((line =bufr.readLine())!=null){

                     //结束标记

                    if(line.equals("over"))

                           break;

                    out.println(line);

                     //out.flush();

              }

              out.close();

              bufr.close();

       }

}

* // *

-------------------------------------------------------------------------------

【序列流】:将多个输入流合并成一个读取流,并且需要使用Enumeration

import java.io.*;

import java.util.*;

class SequenceDemo

{

       public  static void main(String[] args) throws IOException{

             Vector<FileInputStream> v = new Vector<FileInputStream>();

 

              v.add(newFileInputStream("F:\\Courseware\\JAVA\\MyJavaIO2\\1.txt"));

              v.add(newFileInputStream("F:\\Courseware\\JAVA\\MyJavaIO2\\2.txt"));

              v.add(newFileInputStream("F:\\Courseware\\JAVA\\MyJavaIO2\\3.txt"));

            

             Enumeration<FileInputStream> en = v.elements();

              SequenceInputStreamsis = new SequenceInputStream(en);

 

              FileOutputStreamfos = new FileOutputStream("4.txt");

              byte[] buf = newbyte[1024];

 

              int len = 0;

              while ((len =sis.read(buf))!=-1)

              {

                    fos.write(buf,0,len);

              }

              fos.close();

              sis.close();

       }

}

* // *

【分割文件然后合并碎片】:

* // *

import java.io.*;

import java.util.*;

class SequenceDemo

{

       public  static void main(String[] args) throws IOException{

              //splitFile();

              merge();

       }

       //切割:分次写入

       public static void splitFile()throws IOException{

              FileInputStreamfis = new FileInputStream("G:\\原点.mp3");

 

              FileOutputStreamfos = null;

              byte[] buf = newbyte[1024*1024*4];

              int len = 0;

              int count = 1;

              while ((len=fis.read(buf))!=-1){

                     fos = newFileOutputStream("F:\\Courseware\\JAVA\\"+(count++)+".part");

                    fos.write(buf,0,len);

                    fos.close();

              }

              if(fos!=null)

                    fos.close();

              fis.close();

       }

       //合并:Sequence,将多个输入流合并成一个输出流

       public static voidmerge() throws IOException{

             ArrayList<FileInputStream> al = newArrayList<FileInputStream>();

 

              for (intx=1;x<3 ;x++ ){

                    al.add(new FileInputStream("F:\\Courseware\\JAVA\\"+(x)+".part"));

              }

              finalIterator<FileInputStream> it = al.iterator();

 

             Enumeration<FileInputStream> en = newEnumeration<FileInputStream>()

              {

                     public booleanhasMoreElements(){

                           return it.hasNext();

                     }

                     publicFileInputStream nextElement(){

                           return it.next();

                     }

              };  //匿名内部类

             SequenceInputStream sis = new SequenceInputStream(en);

              FileOutputStreamfos =  newFileOutputStream("yuandian.mp3");

 

              byte[] buf = newbyte[1024*1024];

              int len = 0;

              while ((len = sis.read(buf))!=-1){

                    fos.write(buf,0,len);

              }

              fos.close();

              sis.close();

       }

}

* // *

--------------------------------------------------------------------------

【对象流】:ObjectOutputStream & ObjectInputStream

import java.io.*;

import java.util.*;

class SequenceDemo

{

       public  static void main(String[] args) throws Exception{

              //writeObj();

              readObj();

       }

       public static voidwriteObj()throws IOException{

             ObjectOutputStream oos =

                     newObjectOutputStream(new FileOutputStream("obj.txt"));

 

             oos.writeObject(new Person("mike",26));

              oos.close();

       }

       public static voidreadObj()throws Exception{

             ObjectInputStream ois =

                     newObjectInputStream(new FileInputStream("obj.txt"));

              Person p=(Person)ois.readObject();

 

             System.out.println(p);

              ois.close();

       }

}

class Person implements Serializable

{

       public static finallong serialVersionUID = 42L;//唯一的序列化标识

       String name;

       transient int age;//transient声明一个实例变量,当对象存储时,它的值不需要维持。

       static String country ="cn"; //静态成员是不可以被序列化的,因为不在堆内存中

       Person(String name,intage,String country){

              this.name =name;

              this.age = age;

              this.country =country;

       }

       public StringtoString(){

              returnname+" : "+age;

       }

}

------------------------------------------------------------------------------

【管道流】:IO流与多线程结合

* /

import java.io.*;

class PipedStreamDemo

{

       public  static void main(String[] args) throws Exception{

              PipedInputStreamin = new PipedInputStream();

             PipedOutputStream out = new PipedOutputStream();

 

              Read r =newRead(in);

              Write w = newWrite(out);

            

              newThread(r).start();

              newThread(w).start();

 

       }

}

class Read implements Runnable

{

       privatePipedInputStream in;

       Read(PipedInputStreamin){

              this.in = in;

       }

       public void run(){

              try{

                     byte[]buf = new byte[1024];

                   

                     System.out.println("BeforeReading.Blocking!");

                     int len =in.read(buf);

                    System.out.println("Readed Finished.NonBlocking!");

                   

                     String s= new String(buf,0,len);

                     System.out.println(s);

                    in.close();

              }

              catch(IOException e){

                     throw newRuntimeException("PipedReadFailed");

              }

       }

}

class Write implements Runnable

{

       privatePipedOutputStream out;

       Write(PipedOutputStreamout){

              this.out=out;

       }

       public void run(){

              try{

                    System.out.println("Writing now,wait for 6s");

                     Thread.sleep(6000);

                    out.write("Writed Done......".getBytes());

                    out.close();

              }

              catch (Exceptione){

                     throw newRuntimeException("PipedWritedFailed");

              }

       }

}


0 0