zoukankan      html  css  js  c++  java
  • IO流基础

    java.io的描述:

         通过数据流、序列化和文件系统提供系统输入和输出。

    流:

    流是一个很形象的概念.流是一组有顺序,有起点和终点的字节集合,是对数据传输的总称或抽象。即数据在两设备间的传输成为流。

    流的本质是数据传输,根据数据传输特性将流抽象为各种类,方便更直观的进行数据操作。

    分类:

    根据处理数据类型的不同分为:字符流(reader,writer)和字节流(inputStream,outputStream)。

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

    java流在处理上分为字符流和字节流。

    字符流处理的单元为2个字节的Unicode字符,分别操作字符、字符数组或字符串,而字节流处理单元为1个字节(byte),操作字节和字节数组。

     java内用Unicode编码存储字符,字符流处理类负责将外部的其他编码的字符流和java内的Unicode字符流之间的转换。

    而类InputStreamReader和OutputStreamWriter处理字符流和字节流的转换(将字节流封装成字符流,如new InputStreamReader(System.in)).

    字符流(一次可以处理一个缓冲区)一次操作比字节流(一次一个字节)效率高。

    .字节流和字符流的区别

    1.字节流读取的时候,读到一个字节就返回一个字节;  字符流使用了字节流读到一个或多个字节(中文对应的字节数是两个,在UTF-8码表中是3个字节)时。

    先去查指定的编码表,将查到的字符返回。

    2.字节流可以处理所有类型数据,如:图片,MP3,AVI视频文件,而字符流只能处理字符数据。只要是处理纯文本数据,就要优先考虑使用字符流,除此之外都用字节流。

     JAVA流操作有关的类或者接口:

    java流类图结构:

    1.   输入字节流InputStream

    定义和结构说明:

    从输入字节流的继承图可以看出:

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

    ByteArrayInputStream、StringBufferInputStream、FileInputStream 是三种基本的介质流,它们分别从Byte 数组、StringBuffer、和本地文件中读取数据。PipedInputStream 是从与其它线程共用的管道中读取数据,与Piped  相关的知识后续单独介绍。

    ObjectInputStream 和所有FilterInputStream的子类都是装饰流(装饰器模式的主角)。意思是FileInputStream类可以通过一个String路径名创建一个对象,FileInputStream(String name)。而DataInputStream必须装饰一个类才能返回一个对象,DataInputStream(InputStream in)。如下图示:

    加载中...

    实例操作演示:

    【案例 】读取文件内容

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    /**
     * 字节流
     * 读文件内容
     * */
    import java.io.*;
    class hello{
       public static void main(String[] args) throws IOException {
           String fileName="D:"+File.separator+"hello.txt";
           File f=new File(fileName);
           InputStream in=new FileInputStream(f);
           byte[] b=new byte[1024];
           in.read(b);
           in.close();
           System.out.println(new String(b));
        }
    }

    注意:该示例中由于b字节数组长度为1024,如果文件较小,则会有大量填充空格。我们可以利用in.read(b);的返回值来设计程序,如下案例:

    【案例】读取文件内容

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    /**
     * 字节流
     * 读文件内容
     * */
    import java.io.*;
    class hello{
       public static void main(String[] args) throws IOException {
           String fileName="D:"+File.separator+"hello.txt";
           File f=new File(fileName);
           InputStream in=new FileInputStream(f);
           byte[] b=new byte[1024];
           int len=in.read(b);
           in.close();
           System.out.println("读入长度为:"+len);
           System.out.println(new String(b,0,len));
        }
    }

    注意:观察上面的例子可以看出,我们预先申请了一个指定大小的空间,但是有时候这个空间可能太小,有时候可能太大,我们需要准确的大小,这样节省空间,那么我们可以这样做:

    【案例】读取文件内容

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    /**
     * 字节流
     * 读文件内容,节省空间
     * */
    import java.io.*;
    class hello{
       public static void main(String[] args) throws IOException {
           String fileName="D:"+File.separator+"hello.txt";
           File f=new File(fileName);
           InputStream in=new FileInputStream(f);
           byte[] b=new byte[(int)f.length()];
           in.read(b);
           System.out.println("文件长度为:"+f.length());
           in.close();
           System.out.println(new String(b));
        }
    }

    【案例】逐字节读

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    /**
     * 字节流
     * 读文件内容,节省空间
     * */
    import java.io.*;
    class hello{
       public static void main(String[] args) throws IOException {
           String fileName="D:"+File.separator+"hello.txt";
           File f=new File(fileName);
           InputStream in=new FileInputStream(f);
           byte[] b=new byte[(int)f.length()];
           for (int i = 0; i < b.length; i++) {
               b[i]=(byte)in.read();
           }
           in.close();
           System.out.println(new String(b));
        }
    }

    注意:上面的几个例子都是在知道文件的内容多大,然后才展开的,有时候我们不知道文件有多大,这种情况下,我们需要判断是否独到文件的末尾。

    【案例】字节流读取文件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    /**
     * 字节流
     *读文件
     * */
    import java.io.*;
    class hello{
       public static void main(String[] args) throws IOException {
           String fileName="D:"+File.separator+"hello.txt";
           File f=new File(fileName);
           InputStream in=new FileInputStream(f);
           byte[] b=new byte[1024];
           int count =0;
           int temp=0;
           while((temp=in.read())!=(-1)){
               b[count++]=(byte)temp;
           }
           in.close();
           System.out.println(new String(b));
        }
    }

    注意:当读到文件末尾的时候会返回-1.正常情况下是不会返回-1的。

    【案例】DataInputStream类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    import java.io.DataInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
      
    public class DataOutputStreamDemo{
       public static void main(String[] args) throws IOException{
           File file = new File("d:" + File.separator +"hello.txt");
           DataInputStream input = new DataInputStream(new FileInputStream(file));
           char[] ch = new char[10];
           int count = 0;
           char temp;
           while((temp = input.readChar()) != 'C'){
               ch[count++] = temp;
           }
           System.out.println(ch);
        }
    }

    【案例】PushBackInputStream回退流操作

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import java.io.PushbackInputStream;
      
    /**
     * 回退流操作
     * */
    public class PushBackInputStreamDemo{
        public static void main(String[] args) throwsIOException{
           String str = "hello,rollenholt";
           PushbackInputStream push = null;
           ByteArrayInputStream bat = null;
           bat = new ByteArrayInputStream(str.getBytes());
           push = new PushbackInputStream(bat);
           int temp = 0;
           while((temp = push.read()) != -1){
               if(temp == ','){
                    push.unread(temp);
                    temp = push.read();
                    System.out.print("(回退" +(char) temp + ") ");
               }else{
                    System.out.print((char) temp);
               }
           }
        }
    }

    2.   输出字节流OutputStream

    定义和结构说明:

    IO 中输出字节流的继承图可见上图,可以看出:

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

    ByteArrayOutputStream、FileOutputStream是两种基本的介质流,它们分别向Byte 数组、和本地文件中写入数据。PipedOutputStream 是向与其它线程共用的管道中写入数据,

    ObjectOutputStream 和所有FilterOutputStream的子类都是装饰流。具体例子跟InputStream是对应的。

    实例操作演示:

    【案例】向文件中写入字符串

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

    你也可以一个字节一个字节的写入文件:

    【案例】逐字节写入文件

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

    【案例】向文件中追加新内容

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

    【案例】复制文件

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

    【案例】使用内存操作流将一个大写字母转化为小写字母

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

    【案例】验证管道流:进程间通信

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

    【案例】DataOutputStream类示例

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    import java.io.DataOutputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    public class DataOutputStreamDemo{
       public static void main(String[] args) throws IOException{
           File file = new File("d:" + File.separator +"hello.txt");
           char[] ch = { 'A', 'B', 'C' };
           DataOutputStream out = null;
           out = new DataOutputStream(new FileOutputStream(file));
           for(char temp : ch){
               out.writeChar(temp);
           }
           out.close();
        }
    }

    【案例】ZipOutputStream类

    先看一下ZipOutputStream类的继承关系

    java.lang.Object

      java.io.OutputStream

          java.io.FilterOutputStream

              java.util.zip.DeflaterOutputStream

    java.util.zip.ZipOutputStream

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipOutputStream;
      
    public class ZipOutputStreamDemo1{
       public static void main(String[] args) throws IOException{
           File file = new File("d:" + File.separator +"hello.txt");
           File zipFile = new File("d:" + File.separator +"hello.zip");
           InputStream input = new FileInputStream(file);
           ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(
                    zipFile));
           zipOut.putNextEntry(new ZipEntry(file.getName()));
           // 设置注释
           zipOut.setComment("hello");
           int temp = 0;
           while((temp = input.read()) != -1){
               zipOut.write(temp);
           }
           input.close();
           zipOut.close();
        }
    }

    【案例】ZipOutputStream类压缩多个文件

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

    【案例】ZipFile类展示

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

    【案例】解压缩文件(压缩文件中只有一个文件的情况)

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

    【案例】ZipInputStream类解压缩一个压缩文件中包含多个文件的情况

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipFile;
    import java.util.zip.ZipInputStream;
      
    /**
     * 解压缩一个压缩文件中包含多个文件的情况
     * */
    public class ZipFileDemo3{
       public static void main(String[] args) throws IOException{
            File file = new File("d:" +File.separator + "zipFile.zip");
           File outFile = null;
           ZipFile zipFile = new ZipFile(file);
           ZipInputStream zipInput = new ZipInputStream(new FileInputStream(file));
           ZipEntry entry = null;
            InputStream input = null;
           OutputStream output = null;
           while((entry = zipInput.getNextEntry()) != null){
               System.out.println("解压缩" + entry.getName() + "文件");
               outFile = new File("d:" + File.separator + entry.getName());
               if(!outFile.getParentFile().exists()){
                   outFile.getParentFile().mkdir();
               }
               if(!outFile.exists()){
                    outFile.createNewFile();
               }
               input = zipFile.getInputStream(entry);
               output = new FileOutputStream(outFile);
               int temp = 0;
               while((temp = input.read()) != -1){
                    output.write(temp);
               }
               input.close();
               output.close();
           }
        }
    }

    3.字节流的输入与输出的对应图示

    加载中...

    图中蓝色的为主要的对应部分,红色的部分就是不对应部分。紫色的虚线部分代表这些流一般要搭配使用。从上面的图中可以看出Java IO 中的字节流是极其对称的。哲学上讲“存在及合理”,现在我们看看这些字节流中不太对称的几个类吧!

    4.几个特殊的输入流类分析

    LineNumberInputStream

    主要完成从流中读取数据时,会得到相应的行号,至于什么时候分行、在哪里分行是由改类主动确定的,并不是在原始中有这样一个行号。在输出部分没有对应的部分,我们完全可以自己建立一个LineNumberOutputStream,在最初写入时会有一个基准的行号,以后每次遇到换行时会在下一行添加一个行号,看起来也是可以的。好像更不入流了。

    PushbackInputStream

    其功能是查看最后一个字节,不满意就放入缓冲区。主要用在编译器的语法、词法分析部分。输出部分的BufferedOutputStream 几乎实现相近的功能。

    StringBufferInputStream

    已经被Deprecated,本身就不应该出现在InputStream部分,主要因为String 应该属于字符流的范围。已经被废弃了,当然输出部分也没有必要需要它了!还允许它存在只是为了保持版本的向下兼容而已。

    SequenceInputStream

    可以认为是一个工具类,将两个或者多个输入流当成一个输入流依次读取。完全可以从IO 包中去除,还完全不影响IO 包的结构,却让其更“纯洁”――纯洁的Decorator 模式。

    【案例】将两个文本文件合并为另外一个文本文件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.io.SequenceInputStream;
      
    /**
     * 将两个文本文件合并为另外一个文本文件
     * */
    public class SequenceInputStreamDemo{
        public static voidmain(String[] args) throws IOException{
            File file1 = newFile("d:" + File.separator + "hello1.txt");
            File file2 = newFile("d:" + File.separator + "hello2.txt");
            File file3 = newFile("d:" + File.separator + "hello.txt");
            InputStream input1 =new FileInputStream(file1);
            InputStream input2 =new FileInputStream(file2);
            OutputStream output =new FileOutputStream(file3);
            // 合并流
            SequenceInputStreamsis = new SequenceInputStream(input1, input2);
            int temp = 0;
            while((temp =sis.read()) != -1){
               output.write(temp);
            }
            input1.close();
            input2.close();
            output.close();
            sis.close();
        }
    }

    PrintStream

    也可以认为是一个辅助工具。主要可以向其他输出流,或者FileInputStream 写入数据,本身内部实现还是带缓冲的。本质上是对其它流的综合运用的一个工具而已。一样可以踢出IO 包!System.err和System.out 就是PrintStream 的实例!

    【案例】使用PrintStream进行输出

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    /**
     * 使用PrintStream进行输出
     * */
    import java.io.*;
      
    class hello {
       public static void main(String[] args) throws IOException {
           PrintStream print = new PrintStream(new FileOutputStream(newFile("d:"
                    + File.separator +"hello.txt")));
           print.println(true);
           print.println("Rollen");
           print.close();
        }
    }

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

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

    【案例】使用OutputStream向屏幕上输出内容

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

    【案例】输入输出重定向

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

    【案例】使用System.err重定向

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.PrintStream;
      
    /**
     *System.err重定向这个例子也提示我们可以使用这种方法保存错误信息
     * */
    public class systemErr{
       public static void main(String[] args){
           File file = new File("d:" + File.separator +"hello.txt");
           System.err.println("这些在控制台输出");
           try{
               System.setErr(new PrintStream(new FileOutputStream(file)));
           }catch(FileNotFoundException e){
               e.printStackTrace();
           }
           System.err.println("这些在文件中才能看到哦!");
        }
    }

    【案例】System.in重定向

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    /**
     *System.in重定向
     * */
    public class systemIn{
       public static void main(String[] args){
           File file = new File("d:" + File.separator +"hello.txt");
           if(!file.exists()){
               return;
           }else{
               try{
                    System.setIn(newFileInputStream(file));
               }catch(FileNotFoundException e){
                    e.printStackTrace();
               }
               byte[] bytes = new byte[1024];
               int len = 0;
               try{
                    len = System.in.read(bytes);
               }catch(IOException e){
                    e.printStackTrace();
               }
               System.out.println("读入的内容为:" + new String(bytes, 0, len));
           }
        }
    }

    5.字符输入流Reader

    定义和说明:

    在上面的继承关系图中可以看出:

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

    CharReader、StringReader是两种基本的介质流,它们分别将Char 数组、String中读取数据。PipedReader 是从与其它线程共用的管道中读取数据。

    BufferedReader 很明显就是一个装饰器,它和其子类负责装饰其它Reader 对象。

    FilterReader 是所有自定义具体装饰流的父类,其子类PushbackReader 对Reader 对象进行装饰,会增加一个行号。

    InputStreamReader 是一个连接字节流和字符流的桥梁,它将字节流转变为字符流。FileReader可以说是一个达到此功能、常用的工具类,在其源代码中明显使用了将FileInputStream 转变为Reader 的方法。我们可以从这个类中得到一定的技巧。Reader 中各个类的用途和使用方法基本和InputStream 中的类使用一致。后面会有Reader 与InputStream  的对应关系。

    实例操作演示:

    【案例】从文件中读取内容

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    /**
     * 字符流
     * 从文件中读出内容
     * */
    import java.io.*;
    class hello{
       public static void main(String[] args) throws IOException {
           String fileName="D:"+File.separator+"hello.txt";
           File f=new File(fileName);
           char[] ch=new char[100];
           Reader read=new FileReader(f);
           int count=read.read(ch);
           read.close();
           System.out.println("读入的长度为:"+count);
           System.out.println("内容为"+new String(ch,0,count));
        }
    }

    注意:当然最好采用循环读取的方式,因为我们有时候不知道文件到底有多大。

    【案例】以循环方式从文件中读取内容

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    /**
     * 字符流
     * 从文件中读出内容
     * */
    import java.io.*;
    class hello{
       public static void main(String[] args) throws IOException {
           String fileName="D:"+File.separator+"hello.txt";
           File f=new File(fileName);
           char[] ch=new char[100];
           Reader read=new FileReader(f);
           int temp=0;
           int count=0;
           while((temp=read.read())!=(-1)){
               ch[count++]=(char)temp;
           }
           read.close();
           System.out.println("内容为"+new String(ch,0,count));
        }
    }

    【案例】BufferedReader的小例子

    注意:BufferedReader只能接受字符流的缓冲区,因为每一个中文需要占据两个字节,所以需要将System.in这个字节输入流变为字符输入流,采用:

    BufferedReader buf = new BufferedReader(newInputStreamReader(System.in));

    下面是一个实例:

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

    【案例】Scanner类实例

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    import java.util.Scanner;
    /**
     *Scanner的小例子,从键盘读数据
     * */
    public class ScannerDemo{
        publicstatic void main(String[] args){
           Scanner sca = new Scanner(System.in);
           // 读一个整数
           int temp = sca.nextInt();
           System.out.println(temp);
           //读取浮点数
           float flo=sca.nextFloat();
           System.out.println(flo);
            //读取字符
           //...等等的,都是一些太基础的,就不师范了。
        }
    }

    【案例】Scanner类从文件中读出内容

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;
      
    /**
     *Scanner的小例子,从文件中读内容
     * */
    public class ScannerDemo{
       public static void main(String[] args){
      
           File file = new File("d:" + File.separator +"hello.txt");
           Scanner sca = null;
           try{
               sca = new Scanner(file);
           }catch(FileNotFoundException e){
               e.printStackTrace();
           }
           String str = sca.next();
           System.out.println("从文件中读取的内容是:" + str);
        }
    }

    6.字符输出流Writer

    定义和说明:

    在上面的关系图中可以看出:

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

    CharArrayWriter、StringWriter 是两种基本的介质流,它们分别向Char 数组、String 中写入数据。

    PipedWriter 是向与其它线程共用的管道中写入数据,

    BufferedWriter 是一个装饰器为Writer 提供缓冲功能。

    PrintWriter 和PrintStream 极其类似,功能和使用也非常相似。

    OutputStreamWriter 是OutputStream 到Writer 转换的桥梁,它的子类FileWriter 其实就是一个实现此功能的具体类(具体可以研究一SourceCode)。功能和使用和OutputStream 极其类似,后面会有它们的对应图。

    实例操作演示:

    【案例】向文件中写入数据

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    /**
     * 字符流
     * 写入数据
     * */
    import java.io.*;
    class hello{
       public static void main(String[] args) throws IOException {
           String fileName="D:"+File.separator+"hello.txt";
           File f=new File(fileName);
           Writer out =new FileWriter(f);
           String str="hello";
           out.write(str);
           out.close();
        }
    }

    注意:这个例子上之前的例子没什么区别,只是你可以直接输入字符串,而不需要你将字符串转化为字节数组。当你如果想问文件中追加内容的时候,可以使用将上面的声明out的哪一行换为:

    Writer out =new FileWriter(f,true);

    这样,当你运行程序的时候,会发现文件内容变为:hellohello如果想在文件中换行的话,需要使用“ ”比如将str变为String str=" hello";这样文件追加的str的内容就会换行了。

    7.字符流的输入与输出的对应

    加载中...

    8.字符流与字节流转换

    转换流的特点:

    (1)其是字符流和字节流之间的桥梁

    (2)可对读取到的字节数据经过指定编码转换成字符

    (3)可对读取到的字符数据经过指定编码转换成字节

    何时使用转换流?

    当字节和字符之间有转换动作时;

    流操作的数据需要编码或解码时。

    具体的对象体现:

    InputStreamReader:字节到字符的桥梁

    OutputStreamWriter:字符到字节的桥梁

    这两个流对象是字符体系中的成员,它们有转换作用,本身又是字符流,所以在构造的时候需要传入字节流对象进来。

    字节流和字符流转换实例:

    【案例】将字节输出流转化为字符输出流

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    /**
     * 将字节输出流转化为字符输出流
     * */
    import java.io.*;
    class hello{
       public static void main(String[] args) throws IOException {
           String fileName= "d:"+File.separator+"hello.txt";
           File file=new File(fileName);
           Writer out=new OutputStreamWriter(new FileOutputStream(file));
           out.write("hello");
           out.close();
        }
    }

    【案例】将字节输入流转换为字符输入流

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    /**
     * 将字节输入流变为字符输入流
     * */
    import java.io.*;
    class hello{
       public static void main(String[] args) throws IOException {
           String fileName= "d:"+File.separator+"hello.txt";
           File file=new File(fileName);
           Reader read=new InputStreamReader(new FileInputStream(file));
           char[] b=new char[100];
           int len=read.read(b);
           System.out.println(new String(b,0,len));
           read.close();
        }
    }

    9.File类

    File类是对文件系统中文件以及文件夹进行封装的对象,可以通过对象的思想来操作文件和文件夹。 File类保存文件或目录的各种元数据信息,包括文件名、文件长度、最后修改时间、是否可读、获取当前文件的路径名,判断指定文件是否存在、获得当前目录中的文件列表,创建、删除文件和目录等方法。

    【案例 】创建一个文件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    import java.io.*;
    class hello{
       public static void main(String[] args) {
           File f=new File("D:\hello.txt");
           try{
               f.createNewFile();
           }catch (Exception e) {
               e.printStackTrace();
           }
        }
    }

    【案例2】File类的两个常量

    1
    2
    3
    4
    5
    6
    7
    import java.io.*;
    class hello{
       public static void main(String[] args) {
           System.out.println(File.separator);
           System.out.println(File.pathSeparator);
        }
    }

    此处多说几句:有些同学可能认为,我直接在windows下使用进行分割不行吗?当然是可以的。但是在linux下就不是了。所以,要想使得我们的代码跨平台,更加健壮,所以,大家都采用这两个常量吧,其实也多写不了几行。

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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    import java.io.*;
    class hello{
       public static void main(String[] args) {
           String fileName="D:"+File.separator+"hello.txt";
           File f=new File(fileName);
           try{
               f.createNewFile();
           }catch (Exception e) {
               e.printStackTrace();
           }
        }
    }

    【案例4】删除一个文件(或者文件夹)

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

    【案例5】创建一个文件夹

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    /**
     * 创建一个文件夹
     * */
    import java.io.*;
    class hello{
       public static void main(String[] args) {
           String fileName="D:"+File.separator+"hello";
           File f=new File(fileName);
           f.mkdir();
        }
    }

    【案例6】列出目录下的所有文件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    /**
     * 使用list列出指定目录的全部文件
     * */
    import java.io.*;
    class hello{
       public static void main(String[] args) {
           String fileName="D:"+File.separator;
           File f=new File(fileName);
           String[] str=f.list();
           for (int i = 0; i < str.length; i++) {
               System.out.println(str[i]);
           }
        }
    }

    注意使用list返回的是String数组,。而且列出的不是完整路径,如果想列出完整路径的话,需要使用listFiles.它返回的是File的数组。

    【案例7】列出指定目录的全部文件(包括隐藏文件):

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    /**
     * 使用listFiles列出指定目录的全部文件
     * listFiles输出的是完整路径
     * */
    import java.io.*;
    class hello{
       public static void main(String[] args) {
           String fileName="D:"+File.separator;
           File f=new File(fileName);
           File[] str=f.listFiles();
           for (int i = 0; i < str.length; i++) {
               System.out.println(str[i]);
           }
        }
    }

    【案例8】判断一个指定的路径是否为目录

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    /**
     * 使用isDirectory判断一个指定的路径是否为目录
     * */
    import java.io.*;
    class hello{
       public static void main(String[] args) {
           String fileName="D:"+File.separator;
           File f=new File(fileName);
           if(f.isDirectory()){
               System.out.println("YES");
           }else{
               System.out.println("NO");
           }
        }
    }

    【案例9】递归搜索指定目录的全部内容,包括文件和文件夹

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

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

    ( 一 )以字节为导向的 stream------InputStream/OutputStream

    InputStream

    java.io.InputStream 类是其他字节输入流的基类,是抽象类。,一字节为单位读入数据。System.in也是属于这个类的拓展

    它提供的方法方法有

    方法摘要
    int available() 返回此输入流下一个方法调用可以不受阻塞地从此输入流读取(或跳过)的估计字节数。
    void close() 关闭此输入流并释放与该流关联的所有系统资源。
    void mark(int readlimit) 在此输入流中标记当前的位置。
    boolean markSupported() 测试此输入流是否支持 markreset方法。
    abstract int read() 从输入流中读取数据的下一个字节。
    int read(byte[] b) 从输入流中读取一定数量的字节,并将其存储在缓冲区数组 b 中。
    int read(byte[] b, int off, int len) 将输入流中最多 len 个数据字节读入 byte 数组。
    void reset() 将此流重新定位到最后一次对此输入流调用 mark 方法时的位置。
    long skip(long n) 跳过和丢弃此输入流中数据的 n 个字节。

    1.1

    ByteArrayInputStream -- 把内存中的一个缓冲区作为 InputStream 使用 .

    construct---

    (A)ByteArrayInputStream(byte[]) 创建一个新字节数组输入流( ByteArrayInputStream ),它从指定字节数组中读取数据( 使用 byte 作为其缓冲区数组)

    (B)---ByteArrayInputStream(byte[], int, int) 创建一个新字节数组输入流,它从指定字节数组中读取数据。

    ---mark:: 该字节数组未被复制。

    1.2

    StringBufferInputStream -- 把一个 String 对象作为 InputStream .

    construct---

    StringBufferInputStream(String) 据指定串创建一个读取数据的输入流串。

     

    注释:不推荐使用 StringBufferInputStream 方法。 此类不能将字符正确的转换为字节。

    同 JDK 1.1 版中的类似,从一个串创建一个流的最佳方法是采用 StringReader 类。

    1.3

    FileInputStream -- 把一个文件作为 InputStream ,实现对文件的读取操作

    construct---

    (A)FileInputStream(File name) 创建一个输入文件流,从指定的 File 对象读取数据。

    (B)FileInputStream(FileDescriptor) 创建一个输入文件流,从指定的文件描述器读取数据。

    (C)-FileInputStream(String name) 创建一个输入文件流,从指定名称的文件读取数据。

    method ---- read() 从当前输入流中读取一字节数据。

    read(byte[]) 将当前输入流中 b.length 个字节数据读到一个字节数组中。

    read(byte[], int, int) 将输入流中 len 个字节数据读入一个字节数组中。

    1.4

    PipedInputStream :实现了 pipe 的概念,主要在线程中使用 . 管道输入流是指一个通讯管道的接收端。

    一个线程通过管道输出流发送数据,而另一个线程通过管道输入流读取数据,这样可实现两个线程间的通讯。

    construct---

    PipedInputStream() 创建一个管道输入流,它还未与一个管道输出流连接。

    PipedInputStream(PipedOutputStream) 创建一个管道输入流 , 它已连接到一个管道输出流。

    1.5

    SequenceInputStream :把多个 InputStream 合并为一个 InputStream . “序列输入流”类允许应用程序把几个输入流连续地合并起来,

    并且使它们像单个输入流一样出现。每个输入流依次被读取,直到到达该流的末尾。

    然后“序列输入流”类关闭这个流并自动地切换到下一个输入流。

    construct---

    SequenceInputStream(Enumeration) 创建一个新的序列输入流,并用指定的输入流的枚举值初始化它。

    SequenceInputStream(InputStream, InputStream) 创建一个新的序列输入流,初始化为首先 读输入流 s1, 然后读输入流 s2 。

    OutputStream

     

    相对的 OutputStream 是所有字节输出流的父类,它也是抽象类,以字节为单位输出数据,它提供的方法有:

     void close()            关闭此输出流并释放与此流有关的所有系统资源。
     void flush()            刷新此输出流并强制写出所有缓冲的输出字节。
     void write(byte[] b)            将 b.length 个字节从指定的 byte 数组写入此输出流。
     void write(byte[] b, int off, int len)            将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此输出流。
    abstract  void write(int b)            将指定的字节写入此输出流。

    2.1

    ByteArrayOutputStream : 把信息存入内存中的一个缓冲区中 . 该类实现一个以字节数组形式写入数据的输出流。

    当数据写入缓冲区时,它自动扩大。用 toByteArray() 和 toString() 能检索数据。

    constructor

    (A)--- ByteArrayOutputStream() 创建一个新的字节数组输出流。

    (B)--- ByteArrayOutputStream() 创建一个新的字节数组输出流。

    (C)--- ByteArrayOutputStream(int) 创建一个新的字节数组输出流,并带有指定大小字节的缓冲区容量。

    toString(String) 根据指定字符编码将缓冲区内容转换为字符串,并将字节转换为字符。

    write(byte[], int, int) 将指定字节数组中从偏移量 off 开始的 len 个字节写入该字节数组输出流。

    write(int) 将指定字节写入该字节数组输出流。

    writeTo(OutputStream) 用 out.write(buf, 0, count) 调用输出流的写方法将该字节数组输出流的全部内容写入指定的输出流参数。

    2.2

    FileOutputStream: 文件输出流是向 File 或 FileDescriptor 输出数据的一个输出流。

    constructor

    (A)FileOutputStream(File name) 创建一个文件输出流,向指定的 File 对象输出数据。

    (B)FileOutputStream(FileDescriptor) 创建一个文件输出流,向指定的文件描述器输出数据。

    (C)FileOutputStream(String name) 创建一个文件输出流,向指定名称的文件输出数据。

    (D)FileOutputStream(String, boolean) 用指定系统的文件名,创建一个输出文件。

    2.3

    PipedOutputStream: 管道输出流是指一个通讯管道的发送端。 一个线程通过管道输出流发送数据,

    而另一个线程通过管道输入流读取数据,这样可实现两个线程间的通讯。

    constructor

    (A)PipedOutputStream() 创建一个管道输出流,它还未与一个管道输入流连接。

    (B)PipedOutputStream(PipedInputStream) 创建一个管道输出流,它已连接到一个管道输入流。

     

     

    3、两种不同导向的 stream 之间的转换

    3.1

    InputStreamReader 和 OutputStreamReader :

    把一个以字节为导向的 stream 转换成一个以字符为导向的 stream 。

    InputStreamReader 类是从字节流到字符流的桥梁:它读入字节,并根据指定的编码方式,将之转换为字符流。

    使用的编码方式可能由名称指定,或平台可接受的缺省编码方式。

    InputStreamReader 的 read() 方法之一的每次调用,可能促使从基本字节输入流中读取一个或多个字节。

    为了达到更高效率,考虑用 BufferedReader 封装 InputStreamReader ,

    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));//(这就是JAVA 传统的读取键盘输入的方法)

    例如: // 实现从键盘输入一个整数

    String s = null;           
    InputStreamReader re = new InputStreamReader(System.in);
                  BufferedReader br = new BufferedReader(re);
                  try {
                  s = br.readLine();
                  System.out.println("s= " + Integer.parseInt(s));
                  br.close();
                  }
                  catch (IOException e)
                  {
                  e.printStackTrace();
                  }
                  catch (NumberFormatException e)// 当应用程序试图将字符串转换成一种数值类型,但该字符串不能转换为适当格式时,抛出该异常。
                  {
                  System.out.println(" 输入的不是数字 ");
                  }

    InputStreamReader(InputStream) 用缺省的字符编码方式,创建一个 InputStreamReader 。

    InputStreamReader(InputStream, String) 用已命名的字符编码方式,创建一个 InputStreamReader 。

     

    OutputStreamWriter 将多个字符写入到一个输出流,根据指定的字符编码将多个字符转换为字节。

    每个 OutputStreamWriter 合并它自己的 CharToByteConverter, 因而是从字符流到字节流的桥梁。

     

    (三)Java IO 的一般使用原则 :

    一、按数据来源(去向)分类:

    1 、是文件: FileInputStream, FileOutputStream, ( 字节流 )FileReader, FileWriter( 字符 )

    2 、是 byte[] : ByteArrayInputStream, ByteArrayOutputStream( 字节流 )

    3 、是 Char[]: CharArrayReader, CharArrayWriter( 字符流 )

    4 、是 String: StringBufferInputStream, StringBufferOuputStream ( 字节流 )StringReader, StringWriter( 字符流 )

    5 、网络数据流: InputStream, OutputStream,( 字节流 ) Reader, Writer( 字符流 )

    二、按是否格式化输出分:

    1 、要格式化输出: PrintStream, PrintWriter

    三、按是否要缓冲分:

    1 、要缓冲: BufferedInputStream, BufferedOutputStream,( 字节流 ) BufferedReader, BufferedWriter( 字符流 )

    四、按数据格式分:

    1 、二进制格式(只要不能确定是纯文本的) : InputStream, OutputStream 及其所有带 Stream 结束的子类

    2 、纯文本格式(含纯英文与汉字或其他编码方式); Reader, Writer 及其所有带 Reader, Writer 的子类

    五、按输入输出分:

    1 、输入: Reader, InputStream 类型的子类

    2 、输出: Writer, OutputStream 类型的子类

    六、特殊需要:

    1 、从 Stream 到 Reader,Writer 的转换类: InputStreamReader, OutputStreamWriter

    2 、对象输入输出: ObjectInputStream, ObjectOutputStream

    3 、进程间通信: PipeInputStream, PipeOutputStream, PipeReader, PipeWriter

    4 、合并输入: SequenceInputStream

    5 、更特殊的需要: PushbackInputStream, PushbackReader, LineNumberInputStream, LineNumberReader

    决定使用哪个类以及它的构造进程的一般准则如下(不考虑特殊需要):

    首先,考虑最原始的数据格式是什么: 原则四

    第二,是输入还是输出:原则五

    第三,是否需要转换流:原则六第 1 点

    第四,数据来源(去向)是什么:原则一

    第五,是否要缓冲:原则三 (特别注明:一定要注意的是 readLine() 是否有定义,有什么比 read, write 更特殊的输入或输出方法)

    第六,是否要格式化输出:原则二

  • 相关阅读:
    导出excel 文件
    导入excel
    django 中自定义过滤器
    机器学习&深度学习资料收集
    USACO Section 1.4 Arithmetic Progressions 解题报告
    POJ-1062 昂贵的聘礼 解题报告
    USACO Section 1.3 Ski Course Design 解题报告
    USACO Section 1.3 Wormholes 解题报告
    USACO Section 1.3 Combination Lock 解题报告
    USACO Section 1.3 Prime Cryptarithm 解题报告
  • 原文地址:https://www.cnblogs.com/zftxdh/p/7171813.html
Copyright © 2011-2022 走看看