IO流详解

来源:互联网 发布:linux deploy下载 编辑:程序博客网 时间:2024/06/08 01:09


一、流的概念和作用。

流是一种有顺序的,有起点和终点的字节集合,是对数据传输的总成或抽象。即数据在两设备之间的传输称之为流,流的本质是数据传输,根据数据传输的特性讲流抽象为各种类,方便更直观的进行数据操作。

二、IO流的分类。

根据数据处理类的不同分为:字符流和字节流。

根据数据流向不同分为:输入流和输出流。

三、字符流和字节流。

字符流的由来:因为数据编码的不同,而有了对字符进行高效操作的流对象,其本质就是基于字节流读取时,去查了指定的码表。字符流和字节流的区别:

(1)读写单位不同:字节流一字节(8bit)为单位,字符流以字符为单位,根据码表映射字符,一次可能读多个字节。

(2)处理对象不同:字节流能处理所有类型的数据(例如图片,avi),而字符流只能处理字符类型的数据。

(3)字节流操作的时候本身是不会用到缓冲区的,是对文件本身的直接操作。而字符流在操作的时候是会用到缓冲区的,通过缓冲区来操作文件。

结论:优先使用字节流,首先因为在硬盘上所有的文件都是以字节的形式进行传输或保存的,包括图片等内容。但是字符流只是在内存中才会形成,所以在开发中字节流使用广泛。

四、输入流和输出流。

对输入流只能进行读操作,对输出流只能进行写操作。程序中根据数据传输的不同特性使用不同的流。

五、输入字节流InputStream。

InputStream是所有输入字节流的父类,它是一个抽象类。

ByteArrayInputStream、StringBufferInputStream、FileInputStream 是三种基本的介质流,它们分别从Byte 数组、StringBuffer、和本地文件中读取数据。PipedInputStream 是从与其它线程共用的管道中读取数据,与Piped 相关的知识后续单独介绍。
ObjectInputStream 和所有FilterInputStream的子类都是装饰流(装饰器模式的主角)。意思是FileInputStream类可以通过一个String路径名创建一个对象,FileInputStream(String name)。而DataInputStream必须装饰一个类才能返回一个对象,DataInputStream(InputStream in)。

讲解Demo。

读取文件,节省空间。

[html] view plain copy
  1. /*  
  2.  * To change this license header, choose License Headers in Project Properties.  
  3.  * To change this template file, choose Tools | Templates  
  4.  * and open the template in the editor.  
  5.  */  
  6.   
  7. package javaio;  
  8.   
  9. import java.io.File;  
  10. import java.io.FileInputStream;  
  11. import java.io.IOException;  
  12. import java.io.InputStream;  
  13.   
  14. /**  
  15.  * 字节流读取文件内容  
  16.  * 节省空间的方式  
  17.  * @author xk  
  18.  */  
  19. public class IoTest {  
  20.       
  21.     public static void main(String[] args) throws IOException {  
  22.           
  23.         String fileName = "D:"+File.separator+"hello.txt";  
  24.         File f = new File(fileName);  
  25.         InputStream in = new FileInputStream(f);  
  26.         byte[] b = new byte[(int)f.length()];  
  27.         in.read(b);  
  28.         System.err.println("长度为="+f.length());  
  29.         in.close();  
  30.         System.err.println(new String(b));  
  31.     }  
  32.       
  33. }  
逐一字节读:

[html] view plain copy
  1. /*  
  2.  * To change this license header, choose License Headers in Project Properties.  
  3.  * To change this template file, choose Tools | Templates  
  4.  * and open the template in the editor.  
  5.  */  
  6.   
  7. package javaio;  
  8.   
  9. import java.io.File;  
  10. import java.io.FileInputStream;  
  11. import java.io.IOException;  
  12. import java.io.InputStream;  
  13.   
  14. /**  
  15.  * 逐字节读  
  16.  * 读取文件内容,节省空间  
  17.  * @author xk  
  18.  */  
  19. public class IoTest {  
  20.       
  21.     public static void main(String[] args) throws IOException {  
  22.           
  23.         String fileName = "D:"+File.separator+"hello.txt";  
  24.         File f = new File(fileName);  
  25.         InputStream in = new FileInputStream(f);  
  26.         byte[] b = new byte[(int)f.length()];  
  27.         for(int i = 0;i< b.length;i++){  
  28.             b[i] = (byte) in.read();  
  29.         }  
  30.         in.close();  
  31.         System.err.println(new String(b));  
  32.     }  
  33.       
  34. }  
注意:上面的几个例子都是在知道文件的内容多大,然后才展开的,有时候我们不知道文件有多大,这种情况下,我们需要判断是否独到文件的末尾。

字节流读取文件:

[html] view plain copy
  1. /*  
  2.  * To change this license header, choose License Headers in Project Properties.  
  3.  * To change this template file, choose Tools | Templates  
  4.  * and open the template in the editor.  
  5.  */  
  6.   
  7. package javaio;  
  8.   
  9. import java.io.File;  
  10. import java.io.FileInputStream;  
  11. import java.io.IOException;  
  12. import java.io.InputStream;  
  13.   
  14. /**  
  15.  * 逐字节读取文件内容  
  16.  * @author xk  
  17.  */  
  18. public class IoTest {  
  19.       
  20.     public static void main(String[] args) throws IOException {  
  21.           
  22.         String fileName = "D:"+File.separator+"hello.txt";  
  23.         File f = new File(fileName);  
  24.         InputStream in = new FileInputStream(f);  
  25.         byte[] b = new byte[1024];  
  26.         int count = 0;  
  27.         int temp = 0;  
  28.         while((temp = in.read())!=(-1)){  
  29.             b[count++] = (byte)temp;  
  30.         }  
  31.         in.close();  
  32.         System.err.println(new String(b));  
  33.     }  
  34.       
  35. }  
注意:当读到文件末尾的时候会返回-1.正常情况下是不会返回-1的。

PushBackInputStream回退流操作:

[html] view plain copy
  1. /*  
  2.  * To change this license header, choose License Headers in Project Properties.  
  3.  * To change this template file, choose Tools | Templates  
  4.  * and open the template in the editor.  
  5.  */  
  6. package javaio;  
  7.   
  8. import java.io.ByteArrayInputStream;  
  9. import java.io.IOException;  
  10. import java.io.PushbackInputStream;  
  11.   
  12. /**  
  13.  * @author xk  
  14.  */  
  15. public class IoTest {  
  16.   
  17.     public static void main(String[] args) throws IOException {  
  18.   
  19.         String str = "hello,rollenholt";  
  20.         PushbackInputStream push = null;  
  21.         ByteArrayInputStream bat = null;  
  22.         bat = new ByteArrayInputStream(str.getBytes());  
  23.         push = new PushbackInputStream(bat);  
  24.         int temp = 0;  
  25.         while ((temp = push.read()) != -1) {  
  26.             if (temp == ',') {  
  27.                 push.unread(temp);  
  28.                 temp = push.read();  
  29.                 System.out.print("(回退" + (char) temp + ") ");  
  30.             } else {  
  31.                 System.out.print((char) temp);  
  32.             }  
  33.         }  
  34.     }  
  35. }  
六、输出字节流OutputStream。

OutputStream是所有输出流的父类,它是一个抽象类。

ByteArrayOutputStream、FileOutputStream是两种基本的介质流,它们分别向Byte 数组、和本地文件中写入数据。PipedOutputStream 是向与其它线程共用的管道中写入数据,
ObjectOutputStream 和所有FilterOutputStream的子类都是装饰流。具体例子跟InputStream是对应的。

实例Demo:

向文件中写入字符串:

[html] view plain copy
  1. /*  
  2.  * To change this license header, choose License Headers in Project Properties.  
  3.  * To change this template file, choose Tools | Templates  
  4.  * and open the template in the editor.  
  5.  */  
  6. package javaio;  
  7.   
  8. import java.io.File;  
  9. import java.io.FileOutputStream;  
  10. import java.io.IOException;  
  11. import java.io.OutputStream;  
  12.   
  13. /**  
  14.  *  
  15.  * @author xk  
  16.  */  
  17. public class OutputStreamDemo {  
  18.   
  19.     public static void main(String[] args) throws IOException {  
  20.   
  21.         String fileName = "D:" + File.separator + "hello.txt";  
  22.         File f = new File(fileName);  
  23.         OutputStream os = new FileOutputStream(f);  
  24.         String str = "xukuntest";  
  25.         byte[] b = str.getBytes();  
  26.         os.write(b);  
  27.         os.close();  
  28.     }  
  29. }  

[html] view plain copy
  1. /**  
  2.  * 字节流  
  3.  * 向文件中一个字节一个字节的写入字符串  
  4.  * */  
  5. import java.io.*;  
  6. class hello{  
  7.    public static void main(String[] args) throws IOException {  
  8.        String fileName="D:"+File.separator+"hello.txt";  
  9.        File f=new File(fileName);  
  10.        OutputStream out =new FileOutputStream(f);  
  11.        String str="Hello World!!";  
  12.        byte[] b=str.getBytes();  
  13.        for (int i = 0; i < b.length; i++) {  
  14.            out.write(b[i]);  
  15.        }  
  16.        out.close();  
  17.     }  
  18. }  

[html] view plain copy
  1. /**  
  2.  * 字节流  
  3.  * 向文件中追加新内容:  
  4.  * */  
  5. import java.io.*;  
  6. class hello{  
  7.    public static void main(String[] args) throws IOException {  
  8.        String fileName="D:"+File.separator+"hello.txt";  
  9.        File f=new File(fileName);  
  10.        OutputStream out =new FileOutputStream(f,true);//true表示追加模式,否则为覆盖  
  11.        String str="Rollen";  
  12.        //String str="\r\nRollen"; 可以换行  
  13.        byte[] b=str.getBytes();  
  14.        for (int i = 0; i < b.length; i++) {  
  15.            out.write(b[i]);  
  16.        }  
  17.        out.close();  
  18.     }  
  19. }  

[html] view plain copy
  1. /**  
  2.  * 文件的复制  
  3.  * */  
  4. import java.io.*;  
  5. class hello{  
  6.    public static void main(String[] args) throws IOException {  
  7.        if(args.length!=2){  
  8.            System.out.println("命令行参数输入有误,请检查");  
  9.            System.exit(1);  
  10.        }  
  11.        File file1=new File(args[0]);  
  12.        File file2=new File(args[1]);  
  13.            
  14.        if(!file1.exists()){  
  15.            System.out.println("被复制的文件不存在");  
  16.            System.exit(1);  
  17.        }  
  18.        InputStream input=new FileInputStream(file1);  
  19.        OutputStream output=new FileOutputStream(file2);  
  20.        if((input!=null)&&(output!=null)){  
  21.            int temp=0;  
  22.            while((temp=input.read())!=(-1)){  
  23.                 output.write(temp);  
  24.            }  
  25.        }  
  26.        input.close();  
  27.        output.close();  
  28.     }  
  29. }  

[html] view plain copy
  1. /**  
  2.  * 使用内存操作流将一个大写字母转化为小写字母  
  3.  * */  
  4. import java.io.*;  
  5. class hello{  
  6.    public static void main(String[] args) throws IOException {  
  7.        String str="ROLLENHOLT";  
  8.        ByteArrayInputStream input=new ByteArrayInputStream(str.getBytes());  
  9.        ByteArrayOutputStream output=new ByteArrayOutputStream();  
  10.        int temp=0;  
  11.        while((temp=input.read())!=-1){  
  12.            char ch=(char)temp;  
  13.            output.write(Character.toLowerCase(ch));  
  14.        }  
  15.        String outStr=output.toString();  
  16.        input.close();  
  17.        output.close();  
  18.        System.out.println(outStr);  
  19.     }  
  20. }  

[html] view plain copy
  1. /**  
  2.  * 验证管道流  
  3.  * */  
  4. import java.io.*;  
  5.     
  6. /**  
  7.  * 消息发送类  
  8.  * */  
  9. class Send implements Runnable{  
  10.    private PipedOutputStream out=null;  
  11.    public Send() {  
  12.        out=new PipedOutputStream();  
  13.     }  
  14.    public PipedOutputStream getOut(){  
  15.        return this.out;  
  16.     }  
  17.    public void run(){  
  18.        String message="hello , Rollen";  
  19.        try{  
  20.            out.write(message.getBytes());  
  21.        }catch (Exception e) {  
  22.            e.printStackTrace();  
  23.        }try{  
  24.            out.close();  
  25.        }catch (Exception e) {  
  26.            e.printStackTrace();  
  27.        }  
  28.     }  
  29. }  
  30.     
  31. /**  
  32.  * 接受消息类  
  33.  * */  
  34. class Recive implements Runnable{  
  35.    private PipedInputStream input=null;  
  36.    public Recive(){  
  37.        this.input=new PipedInputStream();  
  38.     }  
  39.    public PipedInputStream getInput(){  
  40.        return this.input;  
  41.     }  
  42.    public void run(){  
  43.        byte[] b=new byte[1000];  
  44.        int len=0;  
  45.        try{  
  46.            len=this.input.read(b);  
  47.        }catch (Exception e) {  
  48.            e.printStackTrace();  
  49.        }try{  
  50.            input.close();  
  51.        }catch (Exception e) {  
  52.            e.printStackTrace();  
  53.        }  
  54.        System.out.println("接受的内容为 "+(new String(b,0,len)));  
  55.     }  
  56. }  
  57. /**  
  58.  * 测试类  
  59.  * */  
  60. class hello{  
  61.    public static void main(String[] args) throws IOException {  
  62.        Send send=new Send();  
  63.        Recive recive=new Recive();  
  64.         try{  
  65. //管道连接  
  66.            send.getOut().connect(recive.getInput());  
  67.        }catch (Exception e) {  
  68.            e.printStackTrace();  
  69.        }  
  70.        new Thread(send).start();  
  71.        new Thread(recive).start();  
  72.     }  
  73. }  
DataOutputStream类示例
[html] view plain copy
  1. import java.io.DataOutputStream;  
  2. import java.io.File;  
  3. import java.io.FileOutputStream;  
  4. import java.io.IOException;  
  5. public class DataOutputStreamDemo{  
  6.    public static void main(String[] args) throws IOException{  
  7.        File file = new File("d:" + File.separator +"hello.txt");  
  8.        char[] ch = { 'A', 'B', 'C' };  
  9.        DataOutputStream out = null;  
  10.        out = new DataOutputStream(new FileOutputStream(file));  
  11.        for(char temp : ch){  
  12.            out.writeChar(temp);  
  13.        }  
  14.        out.close();  
  15.     }  
  16. }  
java.util.zip.ZipOutputStream

[html] view plain copy
  1. import java.io.File;  
  2. import java.io.FileInputStream;  
  3. import java.io.FileOutputStream;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.util.zip.ZipEntry;  
  7. import java.util.zip.ZipOutputStream;  
  8.     
  9. public class ZipOutputStreamDemo1{  
  10.    public static void main(String[] args) throws IOException{  
  11.        File file = new File("d:" + File.separator +"hello.txt");  
  12.        File zipFile = new File("d:" + File.separator +"hello.zip");  
  13.        InputStream input = new FileInputStream(file);  
  14.        ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(  
  15.                 zipFile));  
  16.        zipOut.putNextEntry(new ZipEntry(file.getName()));  
  17.        // 设置注释  
  18.        zipOut.setComment("hello");  
  19.        int temp = 0;  
  20.        while((temp = input.read()) != -1){  
  21.            zipOut.write(temp);  
  22.        }  
  23.        input.close();  
  24.        zipOut.close();  
  25.     }  
  26. }  
【案例】ZipOutputStream类压缩多个文件
[html] view plain copy
  1. import java.io.File;  
  2. import java.io.FileInputStream;  
  3. import java.io.FileOutputStream;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.util.zip.ZipEntry;  
  7. import java.util.zip.ZipOutputStream;  
  8.     
  9. /**  
  10.  * 一次性压缩多个文件  
  11.  * */  
  12. public class ZipOutputStreamDemo2{  
  13.    public static void main(String[] args) throws IOException{  
  14.        // 要被压缩的文件夹  
  15.        File file = new File("d:" + File.separator +"temp");  
  16.        File zipFile = new File("d:" + File.separator + "zipFile.zip");  
  17.        InputStream input = null;  
  18.        ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(  
  19.                 zipFile));  
  20.        zipOut.setComment("hello");  
  21.        if(file.isDirectory()){  
  22.            File[] files = file.listFiles();  
  23.            for(int i = 0; i < files.length; ++i){  
  24.                 input = newFileInputStream(files[i]);  
  25.                 zipOut.putNextEntry(newZipEntry(file.getName()  
  26.                         + File.separator +files[i].getName()));  
  27.                int temp = 0;  
  28.                 while((temp = input.read()) !=-1){  
  29.                     zipOut.write(temp);  
  30.                 }  
  31.                 input.close();  
  32.            }  
  33.        }  
  34.        zipOut.close();  
  35.     }  
  36. }  
【案例】ZipFile类展示

[html] view plain copy
  1. import java.io.File;  
  2. import java.io.IOException;  
  3. import java.util.zip.ZipFile;  
  4.     
  5. /**  
  6.  *ZipFile演示  
  7.  * */  
  8. public class ZipFileDemo{  
  9.    public static void main(String[] args) throws IOException{  
  10.        File file = new File("d:" + File.separator +"hello.zip");  
  11.        ZipFile zipFile = new ZipFile(file);  
  12.        System.out.println("压缩文件的名称为:" + zipFile.getName());  
  13.     }  
  14. }  
【案例】解压缩文件(压缩文件中只有一个文件的情况)

[html] view plain copy
  1. import java.io.File;  
  2. import java.io.FileOutputStream;  
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.io.OutputStream;  
  6. import java.util.zip.ZipEntry;  
  7. import java.util.zip.ZipFile;  
  8.     
  9. /**  
  10.  * 解压缩文件(压缩文件中只有一个文件的情况)  
  11.  * */  
  12. public class ZipFileDemo2{  
  13.    public static void main(String[] args) throws IOException{  
  14.        File file = new File("d:" + File.separator +"hello.zip");  
  15.        File outFile = new File("d:" + File.separator +"unZipFile.txt");  
  16.        ZipFile zipFile = new ZipFile(file);  
  17.        ZipEntry entry =zipFile.getEntry("hello.txt");  
  18.        InputStream input = zipFile.getInputStream(entry);  
  19.        OutputStream output = new FileOutputStream(outFile);  
  20.        int temp = 0;  
  21.        while((temp = input.read()) != -1){  
  22.            output.write(temp);  
  23.        }  
  24.        input.close();  
  25.        output.close();  
  26.     }  
  27. }  
【案例】ZipInputStream类解压缩一个压缩文件中包含多个文件的情况

[html] view plain copy
  1. import java.io.File;  
  2. import java.io.FileInputStream;  
  3. import java.io.FileOutputStream;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.io.OutputStream;  
  7. import java.util.zip.ZipEntry;  
  8. import java.util.zip.ZipFile;  
  9. import java.util.zip.ZipInputStream;  
  10.     
  11. /**  
  12.  * 解压缩一个压缩文件中包含多个文件的情况  
  13.  * */  
  14. public class ZipFileDemo3{  
  15.    public static void main(String[] args) throws IOException{  
  16.         File file = new File("d:" +File.separator + "zipFile.zip");  
  17.        File outFile = null;  
  18.        ZipFile zipFile = new ZipFile(file);  
  19.        ZipInputStream zipInput = new ZipInputStream(new FileInputStream(file));  
  20.        ZipEntry entry = null;  
  21.         InputStream input = null;  
  22.        OutputStream output = null;  
  23.        while((entry = zipInput.getNextEntry()) != null){  
  24.            System.out.println("解压缩" + entry.getName() + "文件");  
  25.            outFile = new File("d:" + File.separator + entry.getName());  
  26.            if(!outFile.getParentFile().exists()){  
  27.                outFile.getParentFile().mkdir();  
  28.            }  
  29.            if(!outFile.exists()){  
  30.                 outFile.createNewFile();  
  31.            }  
  32.            input = zipFile.getInputStream(entry);  
  33.            output = new FileOutputStream(outFile);  
  34.            int temp = 0;  
  35.            while((temp = input.read()) != -1){  
  36.                 output.write(temp);  
  37.            }  
  38.            input.close();  
  39.            output.close();  
  40.        }  
  41.     }  
  42. }  
七.几个特殊的输入流类分析
LineNumberInputStream
主要完成从流中读取数据时,会得到相应的行号,至于什么时候分行、在哪里分行是由改类主动确定的,并不是在原始中有这样一个行号。在输出部分没有对应的部分,我们完全可以自己建立一个LineNumberOutputStream,在最初写入时会有一个基准的行号,以后每次遇到换行时会在下一行添加一个行号,看起来也是可以的。好像更不入流了。
PushbackInputStream
其功能是查看最后一个字节,不满意就放入缓冲区。主要用在编译器的语法、词法分析部分。输出部分的BufferedOutputStream 几乎实现相近的功能。
StringBufferInputStream
已经被Deprecated,本身就不应该出现在InputStream部分,主要因为String 应该属于字符流的范围。已经被废弃了,当然输出部分也没有必要需要它了!还允许它存在只是为了保持版本的向下兼容而已。
SequenceInputStream
可以认为是一个工具类,将两个或者多个输入流当成一个输入流依次读取。完全可以从IO 包中去除,还完全不影响IO 包的结构,却让其更“纯洁”――纯洁的Decorator 模式。
【案例】将两个文本文件合并为另外一个文本文件
[html] view plain copy
  1. import java.io.File;  
  2. import java.io.FileInputStream;  
  3. import java.io.FileOutputStream;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.io.OutputStream;  
  7. import java.io.SequenceInputStream;  
  8.     
  9. /**  
  10.  * 将两个文本文件合并为另外一个文本文件  
  11.  * */  
  12. public class SequenceInputStreamDemo{  
  13.     public static voidmain(String[] args) throws IOException{  
  14.         File file1 = newFile("d:" + File.separator + "hello1.txt");  
  15.         File file2 = newFile("d:" + File.separator + "hello2.txt");  
  16.         File file3 = newFile("d:" + File.separator + "hello.txt");  
  17.         InputStream input1 =new FileInputStream(file1);  
  18.         InputStream input2 =new FileInputStream(file2);  
  19.         OutputStream output =new FileOutputStream(file3);  
  20.         // 合并流  
  21.         SequenceInputStreamsis = new SequenceInputStream(input1, input2);  
  22.         int temp = 0;  
  23.         while((temp =sis.read()) != -1){  
  24.            output.write(temp);  
  25.         }  
  26.         input1.close();  
  27.         input2.close();  
  28.         output.close();  
  29.         sis.close();  
  30.     }  
  31. }  
PrintStream
也可以认为是一个辅助工具。主要可以向其他输出流,或者FileInputStream 写入数据,本身内部实现还是带缓冲的。本质上是对其它流的综合运用的一个工具而已。一样可以踢出IO 包!System.err和System.out 就是PrintStream 的实例!

【案例】使用PrintStream进行格式化输出

[html] view plain copy
  1. /**  
  2.  * 使用PrintStream进行输出  
  3.  * 并进行格式化  
  4.  * */  
  5. import java.io.*;  
  6. class hello {  
  7.    public static void main(String[] args) throws IOException {  
  8.        PrintStream print = new PrintStream(new FileOutputStream(newFile("d:"  
  9.                 + File.separator +"hello.txt")));  
  10.        String name="Rollen";  
  11.        int age=20;  
  12.        print.printf("姓名:%s. 年龄:%d.",name,age);  
  13.        print.close();  
  14.     }  
  15. }  
【案例】使用OutputStream向屏幕上输出内容

[html] view plain copy
  1. /**  
  2.  * 使用OutputStream向屏幕上输出内容  
  3.  * */  
  4. import java.io.*;  
  5. class hello {  
  6.    public static void main(String[] args) throws IOException {  
  7.        OutputStream out=System.out;  
  8.        try{  
  9.            out.write("hello".getBytes());  
  10.        }catch (Exception e) {  
  11.            e.printStackTrace();  
  12.        }  
  13.        try{  
  14.            out.close();  
  15.        }catch (Exception e) {  
  16.            e.printStackTrace();  
  17.        }  
  18.     }  
  19. }  
【案例】输入输出重定向

[html] view plain copy
  1. import java.io.File;  
  2. import java.io.FileNotFoundException;  
  3. import java.io.FileOutputStream;  
  4. import java.io.PrintStream;  
  5.     
  6. /**  
  7.  * 为System.out.println()重定向输出  
  8.  * */  
  9. public class systemDemo{  
  10.    public static void main(String[] args){  
  11.        // 此刻直接输出到屏幕  
  12.        System.out.println("hello");  
  13.        File file = new File("d:" + File.separator +"hello.txt");  
  14.        try{  
  15.            System.setOut(new PrintStream(new FileOutputStream(file)));  
  16.        }catch(FileNotFoundException e){  
  17.            e.printStackTrace();  
  18.        }  
  19.        System.out.println("这些内容在文件中才能看到哦!");  
  20.     }  
【案例】System.in重定向

[html] view plain copy
  1. import java.io.File;  
  2. import java.io.FileInputStream;  
  3. import java.io.FileNotFoundException;  
  4. import java.io.IOException;  
  5. /**  
  6.  *System.in重定向  
  7.  * */  
  8. public class systemIn{  
  9.    public static void main(String[] args){  
  10.        File file = new File("d:" + File.separator +"hello.txt");  
  11.        if(!file.exists()){  
  12.            return;  
  13.        }else{  
  14.            try{  
  15.                 System.setIn(newFileInputStream(file));  
  16.            }catch(FileNotFoundException e){  
  17.                 e.printStackTrace();  
  18.            }  
  19.            byte[] bytes = new byte[1024];  
  20.            int len = 0;  
  21.            try{  
  22.                 len = System.in.read(bytes);  
  23.            }catch(IOException e){  
  24.                 e.printStackTrace();  
  25.            }  
  26.            System.out.println("读入的内容为:" + new String(bytes, 0, len));  
  27.        }  
  28.     }  
  29. }  
八.字符输入流Reader
定义和说明:
在上面的继承关系图中可以看出:
Reader 是所有的输入字符流的父类,它是一个抽象类。
CharReader、StringReader是两种基本的介质流,它们分别将Char 数组、String中读取数据。PipedReader 是从与其它线程共用的管道中读取数据。
BufferedReader 很明显就是一个装饰器,它和其子类负责装饰其它Reader 对象。
FilterReader 是所有自定义具体装饰流的父类,其子类PushbackReader 对Reader 对象进行装饰,会增加一个行号。
InputStreamReader 是一个连接字节流和字符流的桥梁,它将字节流转变为字符流。FileReader可以说是一个达到此功能、常用的工具类,在其源代码中明显使用了将FileInputStream 转变为Reader 的方法。我们可以从这个类中得到一定的技巧。Reader 中各个类的用途和使用方法基本和InputStream 中的类使用一致。后面会有Reader 与InputStream 的对应关系。
【案例】以循环方式从文件中读取内容
[html] view plain copy
  1. /**  
  2.  * 字符流  
  3.  * 从文件中读出内容  
  4.  * */  
  5. import java.io.*;  
  6. class hello{  
  7.    public static void main(String[] args) throws IOException {  
  8.        String fileName="D:"+File.separator+"hello.txt";  
  9.        File f=new File(fileName);  
  10.        char[] ch=new char[100];  
  11.        Reader read=new FileReader(f);  
  12.        int temp=0;  
  13.        int count=0;  
  14.        while((temp=read.read())!=(-1)){  
  15.            ch[count++]=(char)temp;  
  16.        }  
  17.        read.close();  
  18.        System.out.println("内容为"+new String(ch,0,count));  
  19.     }  
  20. }  

【案例】BufferedReader的小例子
注意:BufferedReader只能接受字符流的缓冲区,因为每一个中文需要占据两个字节,所以需要将System.in这个字节输入流变为字符输入流,采用:
BufferedReader buf = new BufferedReader(newInputStreamReader(System.in));
下面是一个实例:

[html] view plain copy
  1. import java.io.BufferedReader;  
  2. import java.io.IOException;  
  3. import java.io.InputStreamReader;  
  4.     
  5. /**  
  6.  * 使用缓冲区从键盘上读入内容  
  7.  * */  
  8. public class BufferedReaderDemo{  
  9.    public static void main(String[] args){  
  10.        BufferedReader buf = new BufferedReader(  
  11.                 newInputStreamReader(System.in));  
  12.        String str = null;  
  13.        System.out.println("请输入内容");  
  14.        try{  
  15.            str = buf.readLine();  
  16.        }catch(IOException e){  
  17.            e.printStackTrace();  
  18.        }  
  19.        System.out.println("你输入的内容是:" + str);  
  20.     }  
  21. }  
【案例】Scanner类从文件中读出内容

[html] view plain copy
  1. import java.io.File;  
  2. import java.io.FileNotFoundException;  
  3. import java.util.Scanner;  
  4.     
  5. /**  
  6.  *Scanner的小例子,从文件中读内容  
  7.  * */  
  8. public class ScannerDemo{  
  9.    public static void main(String[] args){  
  10.     
  11.        File file = new File("d:" + File.separator +"hello.txt");  
  12.        Scanner sca = null;  
  13.        try{  
  14.            sca = new Scanner(file);  
  15.        }catch(FileNotFoundException e){  
  16.            e.printStackTrace();  
  17.        }  
  18.        String str = sca.next();  
  19.        System.out.println("从文件中读取的内容是:" + str);  
  20.     }  
  21. }  
九.字符输出流Writer
定义和说明:
在上面的关系图中可以看出:
Writer 是所有的输出字符流的父类,它是一个抽象类。
CharArrayWriter、StringWriter 是两种基本的介质流,它们分别向Char 数组、String 中写入数据。
PipedWriter 是向与其它线程共用的管道中写入数据,
BufferedWriter 是一个装饰器为Writer 提供缓冲功能。
PrintWriter 和PrintStream 极其类似,功能和使用也非常相似。
OutputStreamWriter 是OutputStream 到Writer 转换的桥梁,它的子类FileWriter 其实就是一个实现此功能的具体类(具体可以研究一SourceCode)。功能和使用和OutputStream 极其类似,后面会有它们的对应图。
实例操作演示:
【案例】向文件中写入数据
[html] view plain copy
  1. /**  
  2.  * 字符流  
  3.  * 写入数据  
  4.  * */  
  5. import java.io.*;  
  6. class hello{  
  7.    public static void main(String[] args) throws IOException {  
  8.        String fileName="D:"+File.separator+"hello.txt";  
  9.        File f=new File(fileName);  
  10.        Writer out =new FileWriter(f);  
  11.        String str="hello";  
  12.        out.write(str);  
  13.        out.close();  
  14.     }  
  15. }  
注意:这个例子上之前的例子没什么区别,只是你可以直接输入字符串,而不需要你将字符串转化为字节数组。当你如果想问文件中追加内容的时候,可以使用将上面的声明out的哪一行换为:
Writer out =new FileWriter(f,true);
这样,当你运行程序的时候,会发现文件内容变为:hellohello如果想在文件中换行的话,需要使用“\r\n”比如将str变为String str="\r\nhello";这样文件追加的str的内容就会换行了。
十.字符流与字节流转换
转换流的特点:
(1)其是字符流和字节流之间的桥梁
(2)可对读取到的字节数据经过指定编码转换成字符
(3)可对读取到的字符数据经过指定编码转换成字节
何时使用转换流?
当字节和字符之间有转换动作时;
流操作的数据需要编码或解码时。
具体的对象体现:
InputStreamReader:字节到字符的桥梁
OutputStreamWriter:字符到字节的桥梁
这两个流对象是字符体系中的成员,它们有转换作用,本身又是字符流,所以在构造的时候需要传入字节流对象进来。
字节流和字符流转换实例:
【案例】将字节输出流转化为字符输出流
[html] view plain copy
  1. /**  
  2.  * 将字节输出流转化为字符输出流  
  3.  * */  
  4. import java.io.*;  
  5. class hello{  
  6.    public static void main(String[] args) throws IOException {  
  7.        String fileName"d:"+File.separator+"hello.txt";  
  8.        File file=new File(fileName);  
  9.        Writer out=new OutputStreamWriter(new FileOutputStream(file));  
  10.        out.write("hello");  
  11.        out.close();  
  12.     }  
  13. }  
【案例】将字节输入流转换为字符输入流

[html] view plain copy
  1. /**  
  2.  * 将字节输入流变为字符输入流  
  3.  * */  
  4. import java.io.*;  
  5. class hello{  
  6.    public static void main(String[] args) throws IOException {  
  7.        String fileName"d:"+File.separator+"hello.txt";  
  8.        File file=new File(fileName);  
  9.        Reader read=new InputStreamReader(new FileInputStream(file));  
  10.        char[] b=new char[100];  
  11.        int len=read.read(b);  
  12.        System.out.println(new String(b,0,len));  
  13.        read.close();  
  14.     }  
  15. }  
十一.File类
File类是对文件系统中文件以及文件夹进行封装的对象,可以通过对象的思想来操作文件和文件夹。 File类保存文件或目录的各种元数据信息,包括文件名、文件长度、最后修改时间、是否可读、获取当前文件的路径名,判断指定文件是否存在、获得当前目录中的文件列表,创建、删除文件和目录等方法。

【案例 】创建一个文件

[html] view plain copy
  1. import java.io.*;  
  2. class hello{  
  3.    public static void main(String[] args) {  
  4.        File f=new File("D:\\hello.txt");  
  5.        try{  
  6.            f.createNewFile();  
  7.        }catch (Exception e) {  
  8.            e.printStackTrace();  
  9.        }  
  10.     }  
  11. }  
【案例2】File类的两个常量

[html] view plain copy
  1. import java.io.*;  
  2. class hello{  
  3.    public static void main(String[] args) {  
  4.        System.out.println(File.separator);  
  5.        System.out.println(File.pathSeparator);  
  6.     }  
  7. }  
此处多说几句:有些同学可能认为,我直接在windows下使用\进行分割不行吗?当然是可以的。但是在linux下就不是\了。所以,要想使得我们的代码跨平台,更加健壮,所以,大家都采用这两个常量吧,其实也多写不了几行。

【案例3】File类中的常量改写案例1的代码:

[html] view plain copy
  1. import java.io.*;  
  2. class hello{  
  3.    public static void main(String[] args) {  
  4.        String fileName="D:"+File.separator+"hello.txt";  
  5.        File f=new File(fileName);  
  6.        try{  
  7.            f.createNewFile();  
  8.        }catch (Exception e) {  
  9.            e.printStackTrace();  
  10.        }  
  11.     }  
  12. }  
【案例4】删除一个文件(或者文件夹)

[html] view plain copy
  1. import java.io.*;  
  2. class hello{  
  3.    public static void main(String[] args) {  
  4.        String fileName="D:"+File.separator+"hello.txt";  
  5.        File f=new File(fileName);  
  6.        if(f.exists()){  
  7.            f.delete();  
  8.        }else{  
  9.            System.out.println("文件不存在");  
  10.        }  
  11.            
  12.     }  
  13. }  
【案例5】创建一个文件夹

[html] view plain copy
  1. /**  
  2.  * 创建一个文件夹  
  3.  * */  
  4. import java.io.*;  
  5. class hello{  
  6.    public static void main(String[] args) {  
  7.        String fileName="D:"+File.separator+"hello";  
  8.        File f=new File(fileName);  
  9.        f.mkdir();  
  10.     }  
  11. }  
【案例6】列出目录下的所有文件

[html] view plain copy
  1. /**  
  2.  * 使用list列出指定目录的全部文件  
  3.  * */  
  4. import java.io.*;  
  5. class hello{  
  6.    public static void main(String[] args) {  
  7.        String fileName="D:"+File.separator;  
  8.        File f=new File(fileName);  
  9.        String[] str=f.list();  
  10.        for (int i = 0; i < str.length; i++) {  
  11.            System.out.println(str[i]);  
  12.        }  
  13.     }  
  14. }  
【案例7】递归搜索指定目录的全部内容,包括文件和文件夹
[html] view plain copy
  1. * 列出指定目录的全部内容  
  2.  * */  
  3. import java.io.*;  
  4. class hello{  
  5.    public static void main(String[] args) {  
  6.        String fileName="D:"+File.separator;  
  7.        File f=new File(fileName);  
  8.        print(f);  
  9.     }  
  10.    public static void print(File f){  
  11.        if(f!=null){  
  12.            if(f.isDirectory()){  
  13.                 File[] fileArray=f.listFiles();  
  14.                 if(fileArray!=null){  
  15.                     for (int i = 0; i <filearray.length; i++)="" {="" 递归调用="" print(filearray[i]);="" }="" else{="" system.out.println(f);="" }<="" pre="">  
  16. <p></p>  
  17. <h2>10.RandomAccessFile类</h2>  
  18. <p>该对象并不是流体系中的一员,其封装了字节流,同时还封装了一个缓冲区(字符数组),通过内部的指针来操作字符数组中的数据。该对象特点:</p>  
  19. <p>该对象只能操作文件,所以构造函数接收两种类型的参数:a.字符串文件路径;b.File对象。</p>  
  20. <p>该对象既可以对文件进行读操作,也能进行写操作,在进行对象实例化时可指定操作模式(r,rw)</p>  
  21. <p>注意:该对象在实例化时,如果要操作的文件不存在,会自动创建;如果文件存在,写数据未指定位置,会从头开始写,即覆盖原有的内容。可以用于多线程下载或多个线程同时写数据到文件。</p>  
  22. <p align="left">【案例】使用RandomAccessFile写入文件</p>  
  23. <p align="left"></p>  
  24. <pre class="brush:java;">/**  
  25.  * 使用RandomAccessFile写入文件  
  26.  * */  
  27. import java.io.*;  
  28. class hello{  
  29.     public static void main(String[]args) throws IOException {  
  30.         StringfileName="D:"+File.separator+"hello.txt";  
  31.         File f=new File(fileName);  
  32.         RandomAccessFile demo=newRandomAccessFile(f,"rw");  
  33.        demo.writeBytes("asdsad");  
  34.         demo.writeInt(12);  
  35.         demo.writeBoolean(true);  
  36.         demo.writeChar('A');  
  37.         demo.writeFloat(1.21f);  
  38.         demo.writeDouble(12.123);  
  39.         demo.close();    
  40.     }  
  41. }</pre>  
  42. <p></p>  
  43. <h1>Java IO流的高级概念</h1>  
  44. <h2>编码问题</h2>  
  45. <p>【案例 】取得本地的默认编码</p>  
  46. <p></p>  
  47. <pre class="brush:java;">/**  
  48.  * 取得本地的默认编码  
  49.  * */  
  50. publicclass CharSetDemo{  
  51.     public static void main(String[] args){  
  52.         System.out.println("系统默认编码为:"+ System.getProperty("file.encoding"));  
  53.     }  
  54. }</pre>  
  55. <p></p>  
  56. <p>【案例 】乱码的产生</p>  
  57. <p></p>  
  58. <pre class="brush:java;">import java.io.File;  
  59. import java.io.FileOutputStream;  
  60. import java.io.IOException;  
  61. import java.io.OutputStream;  
  62.     
  63. /**  
  64.  * 乱码的产生  
  65.  * */  
  66. public class CharSetDemo2{  
  67.     public static void main(String[] args) throws IOException{  
  68.         File file = new File("d:" + File.separator + "hello.txt");  
  69.         OutputStream out = new FileOutputStream(file);  
  70.         byte[] bytes = "你好".getBytes("ISO8859-1");  
  71.         out.write(bytes);  
  72.         out.close();  
  73.     }//输出结果为乱码,系统默认编码为GBK,而此处编码为ISO8859-1  
  74. }</pre>  
  75. <h2>对象的序列化</h2>  
  76. <p>对象序列化就是把一个对象变为二进制数据流的一种方法。</p>  
  77. <p>一个类要想被序列化,就行必须实现java.io.Serializable接口。虽然这个接口中没有任何方法,就如同之前的cloneable接口一样。实现了这个接口之后,就表示这个类具有被序列化的能力。先让我们实现一个具有序列化能力的类吧:</p>  
  78. <p>【案例 】实现具有序列化能力的类</p>  
  79. <p></p>  
  80. <pre class="brush:java;">import java.io.*;  
  81. /**  
  82.  * 实现具有序列化能力的类  
  83.  * */  
  84. public class SerializableDemo implements Serializable{  
  85.     public SerializableDemo(){  
  86.            
  87.     }  
  88.     publicSerializableDemo(String name, int age){  
  89.         this.name=name;  
  90.         this.age=age;  
  91.     }  
  92.     @Override  
  93.     public String toString(){  
  94.         return "姓名:"+name+"  年龄:"+age;  
  95.     }  
  96.     private String name;  
  97.     private int age;  
  98. }</pre>  
  99. <p></p>  
  100. <p>【案例 】序列化一个对象 – ObjectOutputStream</p>  
  101. <p></p>  
  102. <pre class="brush:java;">import java.io.Serializable;  
  103. import java.io.File;  
  104. import java.io.FileOutputStream;  
  105. import java.io.IOException;  
  106. import java.io.ObjectOutputStream;  
  107. /**  
  108.  * 实现具有序列化能力的类  
  109.  * */  
  110. public class Person implements Serializable{  
  111.     public Person(){  
  112.      }  
  113.     public Person(String name,int age){  
  114.         this.name = name;  
  115.         this.age = age;  
  116.     }  
  117.     @Override  
  118.     public String toString(){  
  119.         return "姓名:" +name + "  年龄:" +age;  
  120.     }  
  121.     private String name;  
  122.     private int age;  
  123. }  
  124. /**  
  125.  * 示范ObjectOutputStream  
  126.  * */  
  127. public class ObjectOutputStreamDemo{  
  128.     public static voidmain(String[] args) throws IOException{  
  129.         File file = newFile("d:" + File.separator + "hello.txt");  
  130.         ObjectOutputStream oosnew ObjectOutputStream(new FileOutputStream(  
  131.                 file));  
  132.         oos.writeObject(newPerson("rollen", 20));  
  133.         oos.close();  
  134.     }  
  135. }</pre>  
  136. <p></p>  
  137. <p>【案例 】反序列化—ObjectInputStream</p>  
  138. <p></p>  
  139. <pre class="brush:java;">import java.io.File;  
  140. import java.io.FileInputStream;  
  141. import java.io.ObjectInputStream;  
  142.     
  143. /**  
  144.  * ObjectInputStream示范  
  145.  * */  
  146. public class ObjectInputStreamDemo{  
  147.     public static voidmain(String[] args) throws Exception{  
  148.         File file = new File("d:" +File.separator + "hello.txt");  
  149.         ObjectInputStreaminput = new ObjectInputStream(new FileInputStream(  
  150.                 file));  
  151.         Object obj =input.readObject();  
  152.         input.close();  
  153.         System.out.println(obj);  
  154.     }  
  155. }</pre>  
  156. <p></p>  
  157. <p>注意:被Serializable接口声明的类的对象的属性都将被序列化,但是如果想自定义序列化的内容的时候,就需要实现Externalizable接口。</p>  
  158. <p>当一个类要使用Externalizable这个接口的时候,这个类中必须要有一个无参的构造函数,如果没有的话,在构造的时候会产生异常,这是因为在反序列话的时候会默认调用无参的构造函数。</p>  
  159. <p>现在我们来演示一下序列化和反序列话:</p>  
  160. <p>【案例 】使用Externalizable来定制序列化和反序列化操作</p>  
  161. <p></p>  
  162. <pre class="brush:java;">package IO;  
  163.     
  164. import java.io.Externalizable;  
  165. import java.io.File;  
  166. import java.io.FileInputStream;  
  167. import java.io.FileOutputStream;  
  168. import java.io.IOException;  
  169. import java.io.ObjectInput;  
  170. import java.io.ObjectInputStream;  
  171. import java.io.ObjectOutput;  
  172. import java.io.ObjectOutputStream;  
  173.     
  174. /**  
  175.  * 序列化和反序列化的操作  
  176.  * */  
  177. public class ExternalizableDemo{  
  178.     public static voidmain(String[] args) throws Exception{  
  179.         ser(); // 序列化  
  180.         dser(); // 反序列话  
  181.     }  
  182.     
  183.     public static void ser()throws Exception{  
  184.         File file = newFile("d:" + File.separator + "hello.txt");  
  185.         ObjectOutputStream outnew ObjectOutputStream(new FileOutputStream(  
  186.                 file));  
  187.         out.writeObject(newPerson("rollen", 20));  
  188.         out.close();  
  189.     }  
  190.     
  191.     public static void dser()throws Exception{  
  192.         File file = newFile("d:" + File.separator + "hello.txt");  
  193.         ObjectInputStreaminput = new ObjectInputStream(new FileInputStream(  
  194.                 file));  
  195.         Object obj =input.readObject();  
  196.         input.close();  
  197.        System.out.println(obj);  
  198.     }  
  199. }  
  200.     
  201. class Person implements Externalizable{  
  202.     public Person(){  
  203.     
  204.     }  
  205.     
  206.     public Person(String name,int age){  
  207.         this.name = name;  
  208.         this.age = age;  
  209.     }  
  210.     
  211.     @Override  
  212.     public String toString(){  
  213.         return "姓名:" +name + "  年龄:" +age;  
  214.     }  
  215.     
  216.     // 复写这个方法,根据需要可以保存的属性或者具体内容,在序列化的时候使用  
  217.     @Override  
  218.     public voidwriteExternal(ObjectOutput out) throws IOException{  
  219.        out.writeObject(this.name);  
  220.         out.writeInt(age);  
  221.     }  
  222.     
  223.     // 复写这个方法,根据需要读取内容 反序列话的时候需要  
  224.     @Override  
  225.     public voidreadExternal(ObjectInput in) throws IOException,  
  226.            ClassNotFoundException{  
  227.         this.name = (String)in.readObject();  
  228.         this.age =in.readInt();  
  229.     }  
  230.     
  231.     private String name;  
  232.     private int age;  
  233. }</pre>  
  234. <p></p>  
  235. <p>注意:Serializable接口实现的操作其实是吧一个对象中的全部属性进行序列化,当然也可以使用我们上使用是Externalizable接口以实现部分属性的序列化,但是这样的操作比较麻烦,</p>  
  236. <p>当我们使用Serializable接口实现序列化操作的时候,如果一个对象的某一个属性不想被序列化保存下来,那么我们可以使用transient关键字进行说明:</p>  
  237. <p>【案例 】使用transient关键字定制序列化和反序列化操作</p>  
  238. <p></p>  
  239. <pre class="brush:java;">package IO;  
  240.     
  241. import java.io.File;  
  242. import java.io.FileInputStream;  
  243. import java.io.FileOutputStream;  
  244. import java.io.ObjectInputStream;  
  245. import java.io.ObjectOutputStream;  
  246. import java.io.Serializable;  
  247.     
  248. /**  
  249.  * 序列化和反序列化的操作  
  250.  * */  
  251. public class serDemo{  
  252.     public static voidmain(String[] args) throws Exception{  
  253.         ser(); // 序列化  
  254.         dser(); // 反序列话  
  255.     }  
  256.     
  257.     public static void ser()throws Exception{  
  258.         File file = newFile("d:" + File.separator + "hello.txt");  
  259.         ObjectOutputStream outnew ObjectOutputStream(new FileOutputStream(  
  260.                 file));  
  261.         out.writeObject(newPerson1("rollen", 20));  
  262.         out.close();  
  263.     }  
  264.     
  265.     public static void dser()throws Exception{  
  266.         File file = newFile("d:" + File.separator + "hello.txt");  
  267.         ObjectInputStreaminput = new ObjectInputStream(new FileInputStream(  
  268.                 file));  
  269.         Object obj =input.readObject();  
  270.         input.close();  
  271.        System.out.println(obj);  
  272.     }  
  273. }  
  274.     
  275. class Person1 implements Serializable{  
  276.     public Person1(){  
  277.     
  278.     }  
  279.     
  280.     public Person1(Stringname, int age){  
  281.         this.name = name;  
  282.         this.age = age;  
  283.     }  
  284.     
  285.     @Override  
  286.     public String toString(){  
  287.         return "姓名:" +name + "  年龄:" +age;  
  288.     }  
  289.     
  290.     // 注意这里  
  291.     private transient Stringname;  
  292.     private int age;  
  293. }</pre>  
  294. <p></p>  
  295. <p>【运行结果】:</p>  
  296. <p>姓名:null  年龄:20</p>  
  297. <p>【案例 】序列化一组对象</p>  
  298. <p></p>  
  299. <pre class="brush:java;">import java.io.File;  
  300. import java.io.FileInputStream;  
  301. import java.io.FileOutputStream;  
  302. import java.io.ObjectInputStream;  
  303. import java.io.ObjectOutputStream;  
  304. import java.io.Serializable;  
  305.     
  306. /**  
  307.  * 序列化一组对象  
  308.  * */  
  309. public class SerDemo1{  
  310.     public static voidmain(String[] args) throws Exception{  
  311.         Student[] stu = { newStudent("hello", 20), new Student("world", 30),  
  312.                 newStudent("rollen", 40) };  
  313.         ser(stu);  
  314.         Object[] obj = dser();  
  315.         for(int i = 0; i <obj.length; ++i){="" student="" s="(Student)" obj[i];="" system.out.println(s);="" }="" 序列化="" public="" static="" voidser(object[]="" obj)="" throws="" exception{="" file="" +="" file.separator="" "hello.txt");="" objectoutputstream="" out="new" objectoutputstream(new="" fileoutputstream(="" file));="" out.writeobject(obj);="" out.close();="" 反序列化="" object[]dser()="" objectinputstreaminput="new" objectinputstream(new="" fileinputstream(="" object[]="" obj="(Object[])" input.readobject();="" input.close();="" return="" obj;="" class="" implements="" serializable{="" student(){="" student(stringname,="" int="" age){="" this.name="name;" this.age="age;" @override="" string="" tostring(){="" "姓名:="" "="" name="" 年龄:"="" age;="" private="" name;="" }<="" pre="">  
  316. <h1>参考文献:</h1>  
  317. <p>1、http://www.cnblogs.com/rollenholt/archive/2011/09/11/2173787.html</p>  
  318. <p>2、http://www.cnblogs.com/oubo/archive/2012/01/06/2394638.html</p>  
  319. <h3></h3>                       </obj.length;></pre></filearray.lengt<span style="font-family: Consolas, 'Bitstream Vera Sans Mono', 'Courier New', Courier, monospace; font-size: 14px; line-height: 15.390625px; white-space: pre;">h;></span>  

一、流的概念和作用。

流是一种有顺序的,有起点和终点的字节集合,是对数据传输的总成或抽象。即数据在两设备之间的传输称之为流,流的本质是数据传输,根据数据传输的特性讲流抽象为各种类,方便更直观的进行数据操作。

二、IO流的分类。

根据数据处理类的不同分为:字符流和字节流。

根据数据流向不同分为:输入流和输出流。

三、字符流和字节流。

字符流的由来:因为数据编码的不同,而有了对字符进行高效操作的流对象,其本质就是基于字节流读取时,去查了指定的码表。字符流和字节流的区别:

(1)读写单位不同:字节流一字节(8bit)为单位,字符流以字符为单位,根据码表映射字符,一次可能读多个字节。

(2)处理对象不同:字节流能处理所有类型的数据(例如图片,avi),而字符流只能处理字符类型的数据。

(3)字节流操作的时候本身是不会用到缓冲区的,是对文件本身的直接操作。而字符流在操作的时候是会用到缓冲区的,通过缓冲区来操作文件。

结论:优先使用字节流,首先因为在硬盘上所有的文件都是以字节的形式进行传输或保存的,包括图片等内容。但是字符流只是在内存中才会形成,所以在开发中字节流使用广泛。

四、输入流和输出流。

对输入流只能进行读操作,对输出流只能进行写操作。程序中根据数据传输的不同特性使用不同的流。

五、输入字节流InputStream。

InputStream是所有输入字节流的父类,它是一个抽象类。

ByteArrayInputStream、StringBufferInputStream、FileInputStream 是三种基本的介质流,它们分别从Byte 数组、StringBuffer、和本地文件中读取数据。PipedInputStream 是从与其它线程共用的管道中读取数据,与Piped 相关的知识后续单独介绍。
ObjectInputStream 和所有FilterInputStream的子类都是装饰流(装饰器模式的主角)。意思是FileInputStream类可以通过一个String路径名创建一个对象,FileInputStream(String name)。而DataInputStream必须装饰一个类才能返回一个对象,DataInputStream(InputStream in)。

讲解Demo。

读取文件,节省空间。

[html] view plain copy
  1. /*  
  2.  * To change this license header, choose License Headers in Project Properties.  
  3.  * To change this template file, choose Tools | Templates  
  4.  * and open the template in the editor.  
  5.  */  
  6.   
  7. package javaio;  
  8.   
  9. import java.io.File;  
  10. import java.io.FileInputStream;  
  11. import java.io.IOException;  
  12. import java.io.InputStream;  
  13.   
  14. /**  
  15.  * 字节流读取文件内容  
  16.  * 节省空间的方式  
  17.  * @author xk  
  18.  */  
  19. public class IoTest {  
  20.       
  21.     public static void main(String[] args) throws IOException {  
  22.           
  23.         String fileName = "D:"+File.separator+"hello.txt";  
  24.         File f = new File(fileName);  
  25.         InputStream in = new FileInputStream(f);  
  26.         byte[] b = new byte[(int)f.length()];  
  27.         in.read(b);  
  28.         System.err.println("长度为="+f.length());  
  29.         in.close();  
  30.         System.err.println(new String(b));  
  31.     }  
  32.       
  33. }  
逐一字节读:

[html] view plain copy
  1. /*  
  2.  * To change this license header, choose License Headers in Project Properties.  
  3.  * To change this template file, choose Tools | Templates  
  4.  * and open the template in the editor.  
  5.  */  
  6.   
  7. package javaio;  
  8.   
  9. import java.io.File;  
  10. import java.io.FileInputStream;  
  11. import java.io.IOException;  
  12. import java.io.InputStream;  
  13.   
  14. /**  
  15.  * 逐字节读  
  16.  * 读取文件内容,节省空间  
  17.  * @author xk  
  18.  */  
  19. public class IoTest {  
  20.       
  21.     public static void main(String[] args) throws IOException {  
  22.           
  23.         String fileName = "D:"+File.separator+"hello.txt";  
  24.         File f = new File(fileName);  
  25.         InputStream in = new FileInputStream(f);  
  26.         byte[] b = new byte[(int)f.length()];  
  27.         for(int i = 0;i< b.length;i++){  
  28.             b[i] = (byte) in.read();  
  29.         }  
  30.         in.close();  
  31.         System.err.println(new String(b));  
  32.     }  
  33.       
  34. }  
注意:上面的几个例子都是在知道文件的内容多大,然后才展开的,有时候我们不知道文件有多大,这种情况下,我们需要判断是否独到文件的末尾。

字节流读取文件:

[html] view plain copy
  1. /*  
  2.  * To change this license header, choose License Headers in Project Properties.  
  3.  * To change this template file, choose Tools | Templates  
  4.  * and open the template in the editor.  
  5.  */  
  6.   
  7. package javaio;  
  8.   
  9. import java.io.File;  
  10. import java.io.FileInputStream;  
  11. import java.io.IOException;  
  12. import java.io.InputStream;  
  13.   
  14. /**  
  15.  * 逐字节读取文件内容  
  16.  * @author xk  
  17.  */  
  18. public class IoTest {  
  19.       
  20.     public static void main(String[] args) throws IOException {  
  21.           
  22.         String fileName = "D:"+File.separator+"hello.txt";  
  23.         File f = new File(fileName);  
  24.         InputStream in = new FileInputStream(f);  
  25.         byte[] b = new byte[1024];  
  26.         int count = 0;  
  27.         int temp = 0;  
  28.         while((temp = in.read())!=(-1)){  
  29.             b[count++] = (byte)temp;  
  30.         }  
  31.         in.close();  
  32.         System.err.println(new String(b));  
  33.     }  
  34.       
  35. }  
注意:当读到文件末尾的时候会返回-1.正常情况下是不会返回-1的。

PushBackInputStream回退流操作:

[html] view plain copy
  1. /*  
  2.  * To change this license header, choose License Headers in Project Properties.  
  3.  * To change this template file, choose Tools | Templates  
  4.  * and open the template in the editor.  
  5.  */  
  6. package javaio;  
  7.   
  8. import java.io.ByteArrayInputStream;  
  9. import java.io.IOException;  
  10. import java.io.PushbackInputStream;  
  11.   
  12. /**  
  13.  * @author xk  
  14.  */  
  15. public class IoTest {  
  16.   
  17.     public static void main(String[] args) throws IOException {  
  18.   
  19.         String str = "hello,rollenholt";  
  20.         PushbackInputStream push = null;  
  21.         ByteArrayInputStream bat = null;  
  22.         bat = new ByteArrayInputStream(str.getBytes());  
  23.         push = new PushbackInputStream(bat);  
  24.         int temp = 0;  
  25.         while ((temp = push.read()) != -1) {  
  26.             if (temp == ',') {  
  27.                 push.unread(temp);  
  28.                 temp = push.read();  
  29.                 System.out.print("(回退" + (char) temp + ") ");  
  30.             } else {  
  31.                 System.out.print((char) temp);  
  32.             }  
  33.         }  
  34.     }  
  35. }  
六、输出字节流OutputStream。

OutputStream是所有输出流的父类,它是一个抽象类。

ByteArrayOutputStream、FileOutputStream是两种基本的介质流,它们分别向Byte 数组、和本地文件中写入数据。PipedOutputStream 是向与其它线程共用的管道中写入数据,
ObjectOutputStream 和所有FilterOutputStream的子类都是装饰流。具体例子跟InputStream是对应的。

实例Demo:

向文件中写入字符串:

[html] view plain copy
  1. /*  
  2.  * To change this license header, choose License Headers in Project Properties.  
  3.  * To change this template file, choose Tools | Templates  
  4.  * and open the template in the editor.  
  5.  */  
  6. package javaio;  
  7.   
  8. import java.io.File;  
  9. import java.io.FileOutputStream;  
  10. import java.io.IOException;  
  11. import java.io.OutputStream;  
  12.   
  13. /**  
  14.  *  
  15.  * @author xk  
  16.  */  
  17. public class OutputStreamDemo {  
  18.   
  19.     public static void main(String[] args) throws IOException {  
  20.   
  21.         String fileName = "D:" + File.separator + "hello.txt";  
  22.         File f = new File(fileName);  
  23.         OutputStream os = new FileOutputStream(f);  
  24.         String str = "xukuntest";  
  25.         byte[] b = str.getBytes();  
  26.         os.write(b);  
  27.         os.close();  
  28.     }  
  29. }  

[html] view plain copy
  1. /**  
  2.  * 字节流  
  3.  * 向文件中一个字节一个字节的写入字符串  
  4.  * */  
  5. import java.io.*;  
  6. class hello{  
  7.    public static void main(String[] args) throws IOException {  
  8.        String fileName="D:"+File.separator+"hello.txt";  
  9.        File f=new File(fileName);  
  10.        OutputStream out =new FileOutputStream(f);  
  11.        String str="Hello World!!";  
  12.        byte[] b=str.getBytes();  
  13.        for (int i = 0; i < b.length; i++) {  
  14.            out.write(b[i]);  
  15.        }  
  16.        out.close();  
  17.     }  
  18. }  

[html] view plain copy
  1. /**  
  2.  * 字节流  
  3.  * 向文件中追加新内容:  
  4.  * */  
  5. import java.io.*;  
  6. class hello{  
  7.    public static void main(String[] args) throws IOException {  
  8.        String fileName="D:"+File.separator+"hello.txt";  
  9.        File f=new File(fileName);  
  10.        OutputStream out =new FileOutputStream(f,true);//true表示追加模式,否则为覆盖  
  11.        String str="Rollen";  
  12.        //String str="\r\nRollen"; 可以换行  
  13.        byte[] b=str.getBytes();  
  14.        for (int i = 0; i < b.length; i++) {  
  15.            out.write(b[i]);  
  16.        }  
  17.        out.close();  
  18.     }  
  19. }  

[html] view plain copy
  1. /**  
  2.  * 文件的复制  
  3.  * */  
  4. import java.io.*;  
  5. class hello{  
  6.    public static void main(String[] args) throws IOException {  
  7.        if(args.length!=2){  
  8.            System.out.println("命令行参数输入有误,请检查");  
  9.            System.exit(1);  
  10.        }  
  11.        File file1=new File(args[0]);  
  12.        File file2=new File(args[1]);  
  13.            
  14.        if(!file1.exists()){  
  15.            System.out.println("被复制的文件不存在");  
  16.            System.exit(1);  
  17.        }  
  18.        InputStream input=new FileInputStream(file1);  
  19.        OutputStream output=new FileOutputStream(file2);  
  20.        if((input!=null)&&(output!=null)){  
  21.            int temp=0;  
  22.            while((temp=input.read())!=(-1)){  
  23.                 output.write(temp);  
  24.            }  
  25.        }  
  26.        input.close();  
  27.        output.close();  
  28.     }  
  29. }  

[html] view plain copy
  1. /**  
  2.  * 使用内存操作流将一个大写字母转化为小写字母  
  3.  * */  
  4. import java.io.*;  
  5. class hello{  
  6.    public static void main(String[] args) throws IOException {  
  7.        String str="ROLLENHOLT";  
  8.        ByteArrayInputStream input=new ByteArrayInputStream(str.getBytes());  
  9.        ByteArrayOutputStream output=new ByteArrayOutputStream();  
  10.        int temp=0;  
  11.        while((temp=input.read())!=-1){  
  12.            char ch=(char)temp;  
  13.            output.write(Character.toLowerCase(ch));  
  14.        }  
  15.        String outStr=output.toString();  
  16.        input.close();  
  17.        output.close();  
  18.        System.out.println(outStr);  
  19.     }  
  20. }  

[html] view plain copy
  1. /**  
  2.  * 验证管道流  
  3.  * */  
  4. import java.io.*;  
  5.     
  6. /**  
  7.  * 消息发送类  
  8.  * */  
  9. class Send implements Runnable{  
  10.    private PipedOutputStream out=null;  
  11.    public Send() {  
  12.        out=new PipedOutputStream();  
  13.     }  
  14.    public PipedOutputStream getOut(){  
  15.        return this.out;  
  16.     }  
  17.    public void run(){  
  18.        String message="hello , Rollen";  
  19.        try{  
  20.            out.write(message.getBytes());  
  21.        }catch (Exception e) {  
  22.            e.printStackTrace();  
  23.        }try{  
  24.            out.close();  
  25.        }catch (Exception e) {  
  26.            e.printStackTrace();  
  27.        }  
  28.     }  
  29. }  
  30.     
  31. /**  
  32.  * 接受消息类  
  33.  * */  
  34. class Recive implements Runnable{  
  35.    private PipedInputStream input=null;  
  36.    public Recive(){  
  37.        this.input=new PipedInputStream();  
  38.     }  
  39.    public PipedInputStream getInput(){  
  40.        return this.input;  
  41.     }  
  42.    public void run(){  
  43.        byte[] b=new byte[1000];  
  44.        int len=0;  
  45.        try{  
  46.            len=this.input.read(b);  
  47.        }catch (Exception e) {  
  48.            e.printStackTrace();  
  49.        }try{  
  50.            input.close();  
  51.        }catch (Exception e) {  
  52.            e.printStackTrace();  
  53.        }  
  54.        System.out.println("接受的内容为 "+(new String(b,0,len)));  
  55.     }  
  56. }  
  57. /**  
  58.  * 测试类  
  59.  * */  
  60. class hello{  
  61.    public static void main(String[] args) throws IOException {  
  62.        Send send=new Send();  
  63.        Recive recive=new Recive();  
  64.         try{  
  65. //管道连接  
  66.            send.getOut().connect(recive.getInput());  
  67.        }catch (Exception e) {  
  68.            e.printStackTrace();  
  69.        }  
  70.        new Thread(send).start();  
  71.        new Thread(recive).start();  
  72.     }  
  73. }  
DataOutputStream类示例
[html] view plain copy
  1. import java.io.DataOutputStream;  
  2. import java.io.File;  
  3. import java.io.FileOutputStream;  
  4. import java.io.IOException;  
  5. public class DataOutputStreamDemo{  
  6.    public static void main(String[] args) throws IOException{  
  7.        File file = new File("d:" + File.separator +"hello.txt");  
  8.        char[] ch = { 'A', 'B', 'C' };  
  9.        DataOutputStream out = null;  
  10.        out = new DataOutputStream(new FileOutputStream(file));  
  11.        for(char temp : ch){  
  12.            out.writeChar(temp);  
  13.        }  
  14.        out.close();  
  15.     }  
  16. }  
java.util.zip.ZipOutputStream

[html] view plain copy
  1. import java.io.File;  
  2. import java.io.FileInputStream;  
  3. import java.io.FileOutputStream;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.util.zip.ZipEntry;  
  7. import java.util.zip.ZipOutputStream;  
  8.     
  9. public class ZipOutputStreamDemo1{  
  10.    public static void main(String[] args) throws IOException{  
  11.        File file = new File("d:" + File.separator +"hello.txt");  
  12.        File zipFile = new File("d:" + File.separator +"hello.zip");  
  13.        InputStream input = new FileInputStream(file);  
  14.        ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(  
  15.                 zipFile));  
  16.        zipOut.putNextEntry(new ZipEntry(file.getName()));  
  17.        // 设置注释  
  18.        zipOut.setComment("hello");  
  19.        int temp = 0;  
  20.        while((temp = input.read()) != -1){  
  21.            zipOut.write(temp);  
  22.        }  
  23.        input.close();  
  24.        zipOut.close();  
  25.     }  
  26. }  
【案例】ZipOutputStream类压缩多个文件
[html] view plain copy
  1. import java.io.File;  
  2. import java.io.FileInputStream;  
  3. import java.io.FileOutputStream;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.util.zip.ZipEntry;  
  7. import java.util.zip.ZipOutputStream;  
  8.     
  9. /**  
  10.  * 一次性压缩多个文件  
  11.  * */  
  12. public class ZipOutputStreamDemo2{  
  13.    public static void main(String[] args) throws IOException{  
  14.        // 要被压缩的文件夹  
  15.        File file = new File("d:" + File.separator +"temp");  
  16.        File zipFile = new File("d:" + File.separator + "zipFile.zip");  
  17.        InputStream input = null;  
  18.        ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(  
  19.                 zipFile));  
  20.        zipOut.setComment("hello");  
  21.        if(file.isDirectory()){  
  22.            File[] files = file.listFiles();  
  23.            for(int i = 0; i < files.length; ++i){  
  24.                 input = newFileInputStream(files[i]);  
  25.                 zipOut.putNextEntry(newZipEntry(file.getName()  
  26.                         + File.separator +files[i].getName()));  
  27.                int temp = 0;  
  28.                 while((temp = input.read()) !=-1){  
  29.                     zipOut.write(temp);  
  30.                 }  
  31.                 input.close();  
  32.            }  
  33.        }  
  34.        zipOut.close();  
  35.     }  
  36. }  
【案例】ZipFile类展示

[html] view plain copy
  1. import java.io.File;  
  2. import java.io.IOException;  
  3. import java.util.zip.ZipFile;  
  4.     
  5. /**  
  6.  *ZipFile演示  
  7.  * */  
  8. public class ZipFileDemo{  
  9.    public static void main(String[] args) throws IOException{  
  10.        File file = new File("d:" + File.separator +"hello.zip");  
  11.        ZipFile zipFile = new ZipFile(file);  
  12.        System.out.println("压缩文件的名称为:" + zipFile.getName());  
  13.     }  
  14. }  
【案例】解压缩文件(压缩文件中只有一个文件的情况)

[html] view plain copy
  1. import java.io.File;  
  2. import java.io.FileOutputStream;  
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.io.OutputStream;  
  6. import java.util.zip.ZipEntry;  
  7. import java.util.zip.ZipFile;  
  8.     
  9. /**  
  10.  * 解压缩文件(压缩文件中只有一个文件的情况)  
  11.  * */  
  12. public class ZipFileDemo2{  
  13.    public static void main(String[] args) throws IOException{  
  14.        File file = new File("d:" + File.separator +"hello.zip");  
  15.        File outFile = new File("d:" + File.separator +"unZipFile.txt");  
  16.        ZipFile zipFile = new ZipFile(file);  
  17.        ZipEntry entry =zipFile.getEntry("hello.txt");  
  18.        InputStream input = zipFile.getInputStream(entry);  
  19.        OutputStream output = new FileOutputStream(outFile);  
  20.        int temp = 0;  
  21.        while((temp = input.read()) != -1){  
  22.            output.write(temp);  
  23.        }  
  24.        input.close();  
  25.        output.close();  
  26.     }  
  27. }  
【案例】ZipInputStream类解压缩一个压缩文件中包含多个文件的情况

[html] view plain copy
  1. import java.io.File;  
  2. import java.io.FileInputStream;  
  3. import java.io.FileOutputStream;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.io.OutputStream;  
  7. import java.util.zip.ZipEntry;  
  8. import java.util.zip.ZipFile;  
  9. import java.util.zip.ZipInputStream;  
  10.     
  11. /**  
  12.  * 解压缩一个压缩文件中包含多个文件的情况  
  13.  * */  
  14. public class ZipFileDemo3{  
  15.    public static void main(String[] args) throws IOException{  
  16.         File file = new File("d:" +File.separator + "zipFile.zip");  
  17.        File outFile = null;  
  18.        ZipFile zipFile = new ZipFile(file);  
  19.        ZipInputStream zipInput = new ZipInputStream(new FileInputStream(file));  
  20.        ZipEntry entry = null;  
  21.         InputStream input = null;  
  22.        OutputStream output = null;  
  23.        while((entry = zipInput.getNextEntry()) != null){  
  24.            System.out.println("解压缩" + entry.getName() + "文件");  
  25.            outFile = new File("d:" + File.separator + entry.getName());  
  26.            if(!outFile.getParentFile().exists()){  
  27.                outFile.getParentFile().mkdir();  
  28.            }  
  29.            if(!outFile.exists()){  
  30.                 outFile.createNewFile();  
  31.            }  
  32.            input = zipFile.getInputStream(entry);  
  33.            output = new FileOutputStream(outFile);  
  34.            int temp = 0;  
  35.            while((temp = input.read()) != -1){  
  36.                 output.write(temp);  
  37.            }  
  38.            input.close();  
  39.            output.close();  
  40.        }  
  41.     }  
  42. }  
七.几个特殊的输入流类分析
LineNumberInputStream
主要完成从流中读取数据时,会得到相应的行号,至于什么时候分行、在哪里分行是由改类主动确定的,并不是在原始中有这样一个行号。在输出部分没有对应的部分,我们完全可以自己建立一个LineNumberOutputStream,在最初写入时会有一个基准的行号,以后每次遇到换行时会在下一行添加一个行号,看起来也是可以的。好像更不入流了。
PushbackInputStream
其功能是查看最后一个字节,不满意就放入缓冲区。主要用在编译器的语法、词法分析部分。输出部分的BufferedOutputStream 几乎实现相近的功能。
StringBufferInputStream
已经被Deprecated,本身就不应该出现在InputStream部分,主要因为String 应该属于字符流的范围。已经被废弃了,当然输出部分也没有必要需要它了!还允许它存在只是为了保持版本的向下兼容而已。
SequenceInputStream
可以认为是一个工具类,将两个或者多个输入流当成一个输入流依次读取。完全可以从IO 包中去除,还完全不影响IO 包的结构,却让其更“纯洁”――纯洁的Decorator 模式。
【案例】将两个文本文件合并为另外一个文本文件
[html] view plain copy
  1. import java.io.File;  
  2. import java.io.FileInputStream;  
  3. import java.io.FileOutputStream;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.io.OutputStream;  
  7. import java.io.SequenceInputStream;  
  8.     
  9. /**  
  10.  * 将两个文本文件合并为另外一个文本文件  
  11.  * */  
  12. public class SequenceInputStreamDemo{  
  13.     public static voidmain(String[] args) throws IOException{  
  14.         File file1 = newFile("d:" + File.separator + "hello1.txt");  
  15.         File file2 = newFile("d:" + File.separator + "hello2.txt");  
  16.         File file3 = newFile("d:" + File.separator + "hello.txt");  
  17.         InputStream input1 =new FileInputStream(file1);  
  18.         InputStream input2 =new FileInputStream(file2);  
  19.         OutputStream output =new FileOutputStream(file3);  
  20.         // 合并流  
  21.         SequenceInputStreamsis = new SequenceInputStream(input1, input2);  
  22.         int temp = 0;  
  23.         while((temp =sis.read()) != -1){  
  24.            output.write(temp);  
  25.         }  
  26.         input1.close();  
  27.         input2.close();  
  28.         output.close();  
  29.         sis.close();  
  30.     }  
  31. }  
PrintStream
也可以认为是一个辅助工具。主要可以向其他输出流,或者FileInputStream 写入数据,本身内部实现还是带缓冲的。本质上是对其它流的综合运用的一个工具而已。一样可以踢出IO 包!System.err和System.out 就是PrintStream 的实例!

【案例】使用PrintStream进行格式化输出

[html] view plain copy
  1. /**  
  2.  * 使用PrintStream进行输出  
  3.  * 并进行格式化  
  4.  * */  
  5. import java.io.*;  
  6. class hello {  
  7.    public static void main(String[] args) throws IOException {  
  8.        PrintStream print = new PrintStream(new FileOutputStream(newFile("d:"  
  9.                 + File.separator +"hello.txt")));  
  10.        String name="Rollen";  
  11.        int age=20;  
  12.        print.printf("姓名:%s. 年龄:%d.",name,age);  
  13.        print.close();  
  14.     }  
  15. }  
【案例】使用OutputStream向屏幕上输出内容

[html] view plain copy
  1. /**  
  2.  * 使用OutputStream向屏幕上输出内容  
  3.  * */  
  4. import java.io.*;  
  5. class hello {  
  6.    public static void main(String[] args) throws IOException {  
  7.        OutputStream out=System.out;  
  8.        try{  
  9.            out.write("hello".getBytes());  
  10.        }catch (Exception e) {  
  11.            e.printStackTrace();  
  12.        }  
  13.        try{  
  14.            out.close();  
  15.        }catch (Exception e) {  
  16.            e.printStackTrace();  
  17.        }  
  18.     }  
  19. }  
【案例】输入输出重定向

[html] view plain copy
  1. import java.io.File;  
  2. import java.io.FileNotFoundException;  
  3. import java.io.FileOutputStream;  
  4. import java.io.PrintStream;  
  5.     
  6. /**  
  7.  * 为System.out.println()重定向输出  
  8.  * */  
  9. public class systemDemo{  
  10.    public static void main(String[] args){  
  11.        // 此刻直接输出到屏幕  
  12.        System.out.println("hello");  
  13.        File file = new File("d:" + File.separator +"hello.txt");  
  14.        try{  
  15.            System.setOut(new PrintStream(new FileOutputStream(file)));  
  16.        }catch(FileNotFoundException e){  
  17.            e.printStackTrace();  
  18.        }  
  19.        System.out.println("这些内容在文件中才能看到哦!");  
  20.     }  
【案例】System.in重定向

[html] view plain copy
  1. import java.io.File;  
  2. import java.io.FileInputStream;  
  3. import java.io.FileNotFoundException;  
  4. import java.io.IOException;  
  5. /**  
  6.  *System.in重定向  
  7.  * */  
  8. public class systemIn{  
  9.    public static void main(String[] args){  
  10.        File file = new File("d:" + File.separator +"hello.txt");  
  11.        if(!file.exists()){  
  12.            return;  
  13.        }else{  
  14.            try{  
  15.                 System.setIn(newFileInputStream(file));  
  16.            }catch(FileNotFoundException e){  
  17.                 e.printStackTrace();  
  18.            }  
  19.            byte[] bytes = new byte[1024];  
  20.            int len = 0;  
  21.            try{  
  22.                 len = System.in.read(bytes);  
  23.            }catch(IOException e){  
  24.                 e.printStackTrace();  
  25.            }  
  26.            System.out.println("读入的内容为:" + new String(bytes, 0, len));  
  27.        }  
  28.     }  
  29. }  
八.字符输入流Reader
定义和说明:
在上面的继承关系图中可以看出:
Reader 是所有的输入字符流的父类,它是一个抽象类。
CharReader、StringReader是两种基本的介质流,它们分别将Char 数组、String中读取数据。PipedReader 是从与其它线程共用的管道中读取数据。
BufferedReader 很明显就是一个装饰器,它和其子类负责装饰其它Reader 对象。
FilterReader 是所有自定义具体装饰流的父类,其子类PushbackReader 对Reader 对象进行装饰,会增加一个行号。
InputStreamReader 是一个连接字节流和字符流的桥梁,它将字节流转变为字符流。FileReader可以说是一个达到此功能、常用的工具类,在其源代码中明显使用了将FileInputStream 转变为Reader 的方法。我们可以从这个类中得到一定的技巧。Reader 中各个类的用途和使用方法基本和InputStream 中的类使用一致。后面会有Reader 与InputStream 的对应关系。
【案例】以循环方式从文件中读取内容
[html] view plain copy
  1. /**  
  2.  * 字符流  
  3.  * 从文件中读出内容  
  4.  * */  
  5. import java.io.*;  
  6. class hello{  
  7.    public static void main(String[] args) throws IOException {  
  8.        String fileName="D:"+File.separator+"hello.txt";  
  9.        File f=new File(fileName);  
  10.        char[] ch=new char[100];  
  11.        Reader read=new FileReader(f);  
  12.        int temp=0;  
  13.        int count=0;  
  14.        while((temp=read.read())!=(-1)){  
  15.            ch[count++]=(char)temp;  
  16.        }  
  17.        read.close();  
  18.        System.out.println("内容为"+new String(ch,0,count));  
  19.     }  
  20. }  

【案例】BufferedReader的小例子
注意:BufferedReader只能接受字符流的缓冲区,因为每一个中文需要占据两个字节,所以需要将System.in这个字节输入流变为字符输入流,采用:
BufferedReader buf = new BufferedReader(newInputStreamReader(System.in));
下面是一个实例:

[html] view plain copy
  1. import java.io.BufferedReader;  
  2. import java.io.IOException;  
  3. import java.io.InputStreamReader;  
  4.     
  5. /**  
  6.  * 使用缓冲区从键盘上读入内容  
  7.  * */  
  8. public class BufferedReaderDemo{  
  9.    public static void main(String[] args){  
  10.        BufferedReader buf = new BufferedReader(  
  11.                 newInputStreamReader(System.in));  
  12.        String str = null;  
  13.        System.out.println("请输入内容");  
  14.        try{  
  15.            str = buf.readLine();  
  16.        }catch(IOException e){  
  17.            e.printStackTrace();  
  18.        }  
  19.        System.out.println("你输入的内容是:" + str);  
  20.     }  
  21. }  
【案例】Scanner类从文件中读出内容

[html] view plain copy
  1. import java.io.File;  
  2. import java.io.FileNotFoundException;  
  3. import java.util.Scanner;  
  4.     
  5. /**  
  6.  *Scanner的小例子,从文件中读内容  
  7.  * */  
  8. public class ScannerDemo{  
  9.    public static void main(String[] args){  
  10.     
  11.        File file = new File("d:" + File.separator +"hello.txt");  
  12.        Scanner sca = null;  
  13.        try{  
  14.            sca = new Scanner(file);  
  15.        }catch(FileNotFoundException e){  
  16.            e.printStackTrace();  
  17.        }  
  18.        String str = sca.next();  
  19.        System.out.println("从文件中读取的内容是:" + str);  
  20.     }  
  21. }  
九.字符输出流Writer
定义和说明:
在上面的关系图中可以看出:
Writer 是所有的输出字符流的父类,它是一个抽象类。
CharArrayWriter、StringWriter 是两种基本的介质流,它们分别向Char 数组、String 中写入数据。
PipedWriter 是向与其它线程共用的管道中写入数据,
BufferedWriter 是一个装饰器为Writer 提供缓冲功能。
PrintWriter 和PrintStream 极其类似,功能和使用也非常相似。
OutputStreamWriter 是OutputStream 到Writer 转换的桥梁,它的子类FileWriter 其实就是一个实现此功能的具体类(具体可以研究一SourceCode)。功能和使用和OutputStream 极其类似,后面会有它们的对应图。
实例操作演示:
【案例】向文件中写入数据
[html] view plain copy
  1. /**  
  2.  * 字符流  
  3.  * 写入数据  
  4.  * */  
  5. import java.io.*;  
  6. class hello{  
  7.    public static void main(String[] args) throws IOException {  
  8.        String fileName="D:"+File.separator+"hello.txt";  
  9.        File f=new File(fileName);  
  10.        Writer out =new FileWriter(f);  
  11.        String str="hello";  
  12.        out.write(str);  
  13.        out.close();  
  14.     }  
  15. }  
注意:这个例子上之前的例子没什么区别,只是你可以直接输入字符串,而不需要你将字符串转化为字节数组。当你如果想问文件中追加内容的时候,可以使用将上面的声明out的哪一行换为:
Writer out =new FileWriter(f,true);
这样,当你运行程序的时候,会发现文件内容变为:hellohello如果想在文件中换行的话,需要使用“\r\n”比如将str变为String str="\r\nhello";这样文件追加的str的内容就会换行了。
十.字符流与字节流转换
转换流的特点:
(1)其是字符流和字节流之间的桥梁
(2)可对读取到的字节数据经过指定编码转换成字符
(3)可对读取到的字符数据经过指定编码转换成字节
何时使用转换流?
当字节和字符之间有转换动作时;
流操作的数据需要编码或解码时。
具体的对象体现:
InputStreamReader:字节到字符的桥梁
OutputStreamWriter:字符到字节的桥梁
这两个流对象是字符体系中的成员,它们有转换作用,本身又是字符流,所以在构造的时候需要传入字节流对象进来。
字节流和字符流转换实例:
【案例】将字节输出流转化为字符输出流
[html] view plain copy
  1. /**  
  2.  * 将字节输出流转化为字符输出流  
  3.  * */  
  4. import java.io.*;  
  5. class hello{  
  6.    public static void main(String[] args) throws IOException {  
  7.        String fileName"d:"+File.separator+"hello.txt";  
  8.        File file=new File(fileName);  
  9.        Writer out=new OutputStreamWriter(new FileOutputStream(file));  
  10.        out.write("hello");  
  11.        out.close();  
  12.     }  
  13. }  
【案例】将字节输入流转换为字符输入流

[html] view plain copy
  1. /**  
  2.  * 将字节输入流变为字符输入流  
  3.  * */  
  4. import java.io.*;  
  5. class hello{  
  6.    public static void main(String[] args) throws IOException {  
  7.        String fileName"d:"+File.separator+"hello.txt";  
  8.        File file=new File(fileName);  
  9.        Reader read=new InputStreamReader(new FileInputStream(file));  
  10.        char[] b=new char[100];  
  11.        int len=read.read(b);  
  12.        System.out.println(new String(b,0,len));  
  13.        read.close();  
  14.     }  
  15. }  
十一.File类
File类是对文件系统中文件以及文件夹进行封装的对象,可以通过对象的思想来操作文件和文件夹。 File类保存文件或目录的各种元数据信息,包括文件名、文件长度、最后修改时间、是否可读、获取当前文件的路径名,判断指定文件是否存在、获得当前目录中的文件列表,创建、删除文件和目录等方法。

【案例 】创建一个文件

[html] view plain copy
  1. import java.io.*;  
  2. class hello{  
  3.    public static void main(String[] args) {  
  4.        File f=new File("D:\\hello.txt");  
  5.        try{  
  6.            f.createNewFile();  
  7.        }catch (Exception e) {  
  8.            e.printStackTrace();  
  9.        }  
  10.     }  
  11. }  
【案例2】File类的两个常量

[html] view plain copy
  1. import java.io.*;  
  2. class hello{  
  3.    public static void main(String[] args) {  
  4.        System.out.println(File.separator);  
  5.        System.out.println(File.pathSeparator);  
  6.     }  
  7. }  
此处多说几句:有些同学可能认为,我直接在windows下使用\进行分割不行吗?当然是可以的。但是在linux下就不是\了。所以,要想使得我们的代码跨平台,更加健壮,所以,大家都采用这两个常量吧,其实也多写不了几行。

【案例3】File类中的常量改写案例1的代码:

[html] view plain copy
  1. import java.io.*;  
  2. class hello{  
  3.    public static void main(String[] args) {  
  4.        String fileName="D:"+File.separator+"hello.txt";  
  5.        File f=new File(fileName);  
  6.        try{  
  7.            f.createNewFile();  
  8.        }catch (Exception e) {  
  9.            e.printStackTrace();  
  10.        }  
  11.     }  
  12. }  
【案例4】删除一个文件(或者文件夹)

[html] view plain copy
  1. import java.io.*;  
  2. class hello{  
  3.    public static void main(String[] args) {  
  4.        String fileName="D:"+File.separator+"hello.txt";  
  5.        File f=new File(fileName);  
  6.        if(f.exists()){  
  7.            f.delete();  
  8.        }else{  
  9.            System.out.println("文件不存在");  
  10.        }  
  11.            
  12.     }  
  13. }  
【案例5】创建一个文件夹

[html] view plain copy
  1. /**  
  2.  * 创建一个文件夹  
  3.  * */  
  4. import java.io.*;  
  5. class hello{  
  6.    public static void main(String[] args) {  
  7.        String fileName="D:"+File.separator+"hello";  
  8.        File f=new File(fileName);  
  9.        f.mkdir();  
  10.     }  
  11. }  
【案例6】列出目录下的所有文件

[html] view plain copy
  1. /**  
  2.  * 使用list列出指定目录的全部文件  
  3.  * */  
  4. import java.io.*;  
  5. class hello{  
  6.    public static void main(String[] args) {  
  7.        String fileName="D:"+File.separator;  
  8.        File f=new File(fileName);  
  9.        String[] str=f.list();  
  10.        for (int i = 0; i < str.length; i++) {  
  11.            System.out.println(str[i]);  
  12.        }  
  13.     }  
  14. }  
【案例7】递归搜索指定目录的全部内容,包括文件和文件夹
[html] view plain copy
  1. * 列出指定目录的全部内容  
  2.  * */  
  3. import java.io.*;  
  4. class hello{  
  5.    public static void main(String[] args) {  
  6.        String fileName="D:"+File.separator;  
  7.        File f=new File(fileName);  
  8.        print(f);  
  9.     }  
  10.    public static void print(File f){  
  11.        if(f!=null){  
  12.            if(f.isDirectory()){  
  13.                 File[] fileArray=f.listFiles();  
  14.                 if(fileArray!=null){  
  15.                     for (int i = 0; i <filearray.length; i++)="" {="" 递归调用="" print(filearray[i]);="" }="" else{="" system.out.println(f);="" }<="" pre="">  
  16. <p></p>  
  17. <h2>10.RandomAccessFile类</h2>  
  18. <p>该对象并不是流体系中的一员,其封装了字节流,同时还封装了一个缓冲区(字符数组),通过内部的指针来操作字符数组中的数据。该对象特点:</p>  
  19. <p>该对象只能操作文件,所以构造函数接收两种类型的参数:a.字符串文件路径;b.File对象。</p>  
  20. <p>该对象既可以对文件进行读操作,也能进行写操作,在进行对象实例化时可指定操作模式(r,rw)</p>  
  21. <p>注意:该对象在实例化时,如果要操作的文件不存在,会自动创建;如果文件存在,写数据未指定位置,会从头开始写,即覆盖原有的内容。可以用于多线程下载或多个线程同时写数据到文件。</p>  
  22. <p align="left">【案例】使用RandomAccessFile写入文件</p>  
  23. <p align="left"></p>  
  24. <pre class="brush:java;">/**  
  25.  * 使用RandomAccessFile写入文件  
  26.  * */  
  27. import java.io.*;  
  28. class hello{  
  29.     public static void main(String[]args) throws IOException {  
  30.         StringfileName="D:"+File.separator+"hello.txt";  
  31.         File f=new File(fileName);  
  32.         RandomAccessFile demo=newRandomAccessFile(f,"rw");  
  33.        demo.writeBytes("asdsad");  
  34.         demo.writeInt(12);  
  35.         demo.writeBoolean(true);  
  36.         demo.writeChar('A');  
  37.         demo.writeFloat(1.21f);  
  38.         demo.writeDouble(12.123);  
  39.         demo.close();    
  40.     }  
  41. }</pre>  
  42. <p></p>  
  43. <h1>Java IO流的高级概念</h1>  
  44. <h2>编码问题</h2>  
  45. <p>【案例 】取得本地的默认编码</p>  
  46. <p></p>  
  47. <pre class="brush:java;">/**  
  48.  * 取得本地的默认编码  
  49.  * */  
  50. publicclass CharSetDemo{  
  51.     public static void main(String[] args){  
  52.         System.out.println("系统默认编码为:"+ System.getProperty("file.encoding"));  
  53.     }  
  54. }</pre>  
  55. <p></p>  
  56. <p>【案例 】乱码的产生</p>  
  57. <p></p>  
  58. <pre class="brush:java;">import java.io.File;  
  59. import java.io.FileOutputStream;  
  60. import java.io.IOException;  
  61. import java.io.OutputStream;  
  62.     
  63. /**  
  64.  * 乱码的产生  
  65.  * */  
  66. public class CharSetDemo2{  
  67.     public static void main(String[] args) throws IOException{  
  68.         File file = new File("d:" + File.separator + "hello.txt");  
  69.         OutputStream out = new FileOutputStream(file);  
  70.         byte[] bytes = "你好".getBytes("ISO8859-1");  
  71.         out.write(bytes);  
  72.         out.close();  
  73.     }//输出结果为乱码,系统默认编码为GBK,而此处编码为ISO8859-1  
  74. }</pre>  
  75. <h2>对象的序列化</h2>  
  76. <p>对象序列化就是把一个对象变为二进制数据流的一种方法。</p>  
  77. <p>一个类要想被序列化,就行必须实现java.io.Serializable接口。虽然这个接口中没有任何方法,就如同之前的cloneable接口一样。实现了这个接口之后,就表示这个类具有被序列化的能力。先让我们实现一个具有序列化能力的类吧:</p>  
  78. <p>【案例 】实现具有序列化能力的类</p>  
  79. <p></p>  
  80. <pre class="brush:java;">import java.io.*;  
  81. /**  
  82.  * 实现具有序列化能力的类  
  83.  * */  
  84. public class SerializableDemo implements Serializable{  
  85.     public SerializableDemo(){  
  86.            
  87.     }  
  88.     publicSerializableDemo(String name, int age){  
  89.         this.name=name;  
  90.         this.age=age;  
  91.     }  
  92.     @Override  
  93.     public String toString(){  
  94.         return "姓名:"+name+"  年龄:"+age;  
  95.     }  
  96.     private String name;  
  97.     private int age;  
  98. }</pre>  
  99. <p></p>  
  100. <p>【案例 】序列化一个对象 – ObjectOutputStream</p>  
  101. <p></p>  
  102. <pre class="brush:java;">import java.io.Serializable;  
  103. import java.io.File;  
  104. import java.io.FileOutputStream;  
  105. import java.io.IOException;  
  106. import java.io.ObjectOutputStream;  
  107. /**  
  108.  * 实现具有序列化能力的类  
  109.  * */  
  110. public class Person implements Serializable{  
  111.     public Person(){  
  112.      }  
  113.     public Person(String name,int age){  
  114.         this.name = name;  
  115.         this.age = age;  
  116.     }  
  117.     @Override  
  118.     public String toString(){  
  119.         return "姓名:" +name + "  年龄:" +age;  
  120.     }  
  121.     private String name;  
  122.     private int age;  
  123. }  
  124. /**  
  125.  * 示范ObjectOutputStream  
  126.  * */  
  127. public class ObjectOutputStreamDemo{  
  128.     public static voidmain(String[] args) throws IOException{  
  129.         File file = newFile("d:" + File.separator + "hello.txt");  
  130.         ObjectOutputStream oosnew ObjectOutputStream(new FileOutputStream(  
  131.                 file));  
  132.         oos.writeObject(newPerson("rollen", 20));  
  133.         oos.close();  
  134.     }  
  135. }</pre>  
  136. <p></p>  
  137. <p>【案例 】反序列化—ObjectInputStream</p>  
  138. <p></p>  
  139. <pre class="brush:java;">import java.io.File;  
  140. import java.io.FileInputStream;  
  141. import java.io.ObjectInputStream;  
  142.     
  143. /**  
  144.  * ObjectInputStream示范  
  145.  * */  
  146. public class ObjectInputStreamDemo{  
  147.     public static voidmain(String[] args) throws Exception{  
  148.         File file = new File("d:" +File.separator + "hello.txt");  
  149.         ObjectInputStreaminput = new ObjectInputStream(new FileInputStream(  
  150.                 file));  
  151.         Object obj =input.readObject();  
  152.         input.close();  
  153.         System.out.println(obj);  
  154.     }  
  155. }</pre>  
  156. <p></p>  
  157. <p>注意:被Serializable接口声明的类的对象的属性都将被序列化,但是如果想自定义序列化的内容的时候,就需要实现Externalizable接口。</p>  
  158. <p>当一个类要使用Externalizable这个接口的时候,这个类中必须要有一个无参的构造函数,如果没有的话,在构造的时候会产生异常,这是因为在反序列话的时候会默认调用无参的构造函数。</p>  
  159. <p>现在我们来演示一下序列化和反序列话:</p>  
  160. <p>【案例 】使用Externalizable来定制序列化和反序列化操作</p>  
  161. <p></p>  
  162. <pre class="brush:java;">package IO;  
  163.     
  164. import java.io.Externalizable;  
  165. import java.io.File;  
  166. import java.io.FileInputStream;  
  167. import java.io.FileOutputStream;  
  168. import java.io.IOException;  
  169. import java.io.ObjectInput;  
  170. import java.io.ObjectInputStream;  
  171. import java.io.ObjectOutput;  
  172. import java.io.ObjectOutputStream;  
  173.     
  174. /**  
  175.  * 序列化和反序列化的操作  
  176.  * */  
  177. public class ExternalizableDemo{  
  178.     public static voidmain(String[] args) throws Exception{  
  179.         ser(); // 序列化  
  180.         dser(); // 反序列话  
  181.     }  
  182.     
  183.     public static void ser()throws Exception{  
  184.         File file = newFile("d:" + File.separator + "hello.txt");  
  185.         ObjectOutputStream outnew ObjectOutputStream(new FileOutputStream(  
  186.                 file));  
  187.         out.writeObject(newPerson("rollen", 20));  
  188.         out.close();  
  189.     }  
  190.     
  191.     public static void dser()throws Exception{  
  192.         File file = newFile("d:" + File.separator + "hello.txt");  
  193.         ObjectInputStreaminput = new ObjectInputStream(new FileInputStream(  
  194.                 file));  
  195.         Object obj =input.readObject();  
  196.         input.close();  
  197.        System.out.println(obj);  
  198.     }  
  199. }  
  200.     
  201. class Person implements Externalizable{  
  202.     public Person(){  
  203.     
  204.     }  
  205.     
  206.     public Person(String name,int age){  
  207.         this.name = name;  
  208.         this.age = age;  
  209.     }  
  210.     
  211.     @Override  
  212.     public String toString(){  
  213.         return "姓名:" +name + "  年龄:" +age;  
  214.     }  
  215.     
  216.     // 复写这个方法,根据需要可以保存的属性或者具体内容,在序列化的时候使用  
  217.     @Override  
  218.     public voidwriteExternal(ObjectOutput out) throws IOException{  
  219.        out.writeObject(this.name);  
  220.         out.writeInt(age);  
  221.     }  
  222.     
  223.     // 复写这个方法,根据需要读取内容 反序列话的时候需要  
  224.     @Override  
  225.     public voidreadExternal(ObjectInput in) throws IOException,  
  226.            ClassNotFoundException{  
  227.         this.name = (String)in.readObject();  
  228.         this.age =in.readInt();  
  229.     }  
  230.     
  231.     private String name;  
  232.     private int age;  
  233. }</pre>  
  234. <p></p>  
  235. <p>注意:Serializable接口实现的操作其实是吧一个对象中的全部属性进行序列化,当然也可以使用我们上使用是Externalizable接口以实现部分属性的序列化,但是这样的操作比较麻烦,</p>  
  236. <p>当我们使用Serializable接口实现序列化操作的时候,如果一个对象的某一个属性不想被序列化保存下来,那么我们可以使用transient关键字进行说明:</p>  
  237. <p>【案例 】使用transient关键字定制序列化和反序列化操作</p>  
  238. <p></p>  
  239. <pre class="brush:java;">package IO;  
  240.     
  241. import java.io.File;  
  242. import java.io.FileInputStream;  
  243. import java.io.FileOutputStream;  
  244. import java.io.ObjectInputStream;  
  245. import java.io.ObjectOutputStream;  
  246. import java.io.Serializable;  
  247.     
  248. /**  
  249.  * 序列化和反序列化的操作  
  250.  * */  
  251. public class serDemo{  
  252.     public static voidmain(String[] args) throws Exception{  
  253.         ser(); // 序列化  
  254.         dser(); // 反序列话  
  255.     }  
  256.     
  257.     public static void ser()throws Exception{  
  258.         File file = newFile("d:" + File.separator + "hello.txt");  
  259.         ObjectOutputStream outnew ObjectOutputStream(new FileOutputStream(  
  260.                 file));  
  261.         out.writeObject(newPerson1("rollen", 20));  
  262.         out.close();  
  263.     }  
  264.     
  265.     public static void dser()throws Exception{  
  266.         File file = newFile("d:" + File.separator + "hello.txt");  
  267.         ObjectInputStreaminput = new ObjectInputStream(new FileInputStream(  
  268.                 file));  
  269.         Object obj =input.readObject();  
  270.         input.close();  
  271.        System.out.println(obj);  
  272.     }  
  273. }  
  274.     
  275. class Person1 implements Serializable{  
  276.     public Person1(){  
  277.     
  278.     }  
  279.     
  280.     public Person1(Stringname, int age){  
  281.         this.name = name;  
  282.         this.age = age;  
  283.     }  
  284.     
  285.     @Override  
  286.     public String toString(){  
  287.         return "姓名:" +name + "  年龄:" +age;  
  288.     }  
  289.     
  290.     // 注意这里  
  291.     private transient Stringname;  
  292.     private int age;  
  293. }</pre>  
  294. <p></p>  
  295. <p>【运行结果】:</p>  
  296. <p>姓名:null  年龄:20</p>  
  297. <p>【案例 】序列化一组对象</p>  
  298. <p></p>  
  299. <pre class="brush:java;">import java.io.File;  
  300. import java.io.FileInputStream;  
  301. import java.io.FileOutputStream;  
  302. import java.io.ObjectInputStream;  
  303. import java.io.ObjectOutputStream;  
  304. import java.io.Serializable;  
  305.     
  306. /**  
  307.  * 序列化一组对象  
  308.  * */  
  309. public class SerDemo1{  
  310.     public static voidmain(String[] args) throws Exception{  
  311.         Student[] stu = { newStudent("hello", 20), new Student("world", 30),  
  312.                 newStudent("rollen", 40) };  
  313.         ser(stu);  
  314.         Object[] obj = dser();  
  315.         for(int i = 0; i <obj.length; ++i){="" student="" s="(Student)" obj[i];="" system.out.println(s);="" }="" 序列化="" public="" static="" voidser(object[]="" obj)="" throws="" exception{="" file="" +="" file.separator="" "hello.txt");="" objectoutputstream="" out="new" objectoutputstream(new="" fileoutputstream(="" file));="" out.writeobject(obj);="" out.close();="" 反序列化="" object[]dser()="" objectinputstreaminput="new" objectinputstream(new="" fileinputstream(="" object[]="" obj="(Object[])" input.readobject();="" input.close();="" return="" obj;="" class="" implements="" serializable{="" student(){="" student(stringname,="" int="" age){="" this.name="name;" this.age="age;" @override="" string="" tostring(){="" "姓名:="" "="" name="" 年龄:"="" age;="" private="" name;="" }<="" pre="">  
  316. <h1>参考文献:</h1>  
  317. <p>1、http://www.cnblogs.com/rollenholt/archive/2011/09/11/2173787.html</p>  
  318. <p>2、http://www.cnblogs.com/oubo/archive/2012/01/06/2394638.html</p>  
  319. <h3></h3>                       </obj.length;></pre></filearray.lengt<span style="font-family: Consolas, 'Bitstream Vera Sans Mono', 'Courier New', Courier, monospace; font-size: 14px; line-height: 15.390625px; white-space: pre;">h;></span>  

原创粉丝点击