流的概念和作用


學習Java IO,不得不提到的就是JavaIO流。

流是一組有順序的,有起點和終點的字節集合,是對數據傳輸的總稱或抽象。即數據在兩設備間的傳輸稱為流,流的本質是數據傳輸,根據數據傳輸特性將流抽象為各種類,方便更直觀的進行數據操作。

IO流的分類

根據處理數據類型的不同分為:字符流和字節流

根據數據流向不同分為:輸入流和輸出流

字符流和字節流

字符流的由來: 因為數據編碼的不同,而有了對字符進行高效操作的流對象。本質其實就是基於字節流讀取時,去查了指定的碼表。字節流和字符流的區別:

(1)讀寫單位不同:字節流以字節(8bit)為單位,字符流以字符為單位,根據碼表映射字符,一次可能讀多個字節。

(2)處理對象不同:字節流能處理所有類型的數據(如圖片、avi等),而字符流只能處理字符類型的數據。

(3)字節流在操作的時候本身是不會用到緩沖區的,是文件本身的直接操作的;而字符流在操作的時候下后是會用到緩沖區的,是通過緩沖區來操作文件,我們將在下面驗證這一點。

結論:優先選用字節流。首先因為硬盤上的所有文件都是以字節的形式進行傳輸或者保存的,包括圖片等內容。但是字符只是在內存中才會形成的,所以在開發中,字節流使用廣泛。

輸入流和輸出流

對輸入流只能進行讀操作,對輸出流只能進行寫操作,程序中需要根據待傳輸數據的不同特性而使用不同的流。

Java流類圖結構:

 

Java IO流對象

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="\r\nRollen"; 可以換行
        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如果想在文件中換行的話,需要使用“\r\n”比如將str變為String str="\r\nhello";這樣文件追加的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
* 列出指定目錄的全部內容
  * */
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

10.RandomAccessFile類

該對象並不是流體系中的一員,其封裝了字節流,同時還封裝了一個緩沖區(字符數組),通過內部的指針來操作字符數組中的數據。該對象特點:

該對象只能操作文件,所以構造函數接收兩種類型的參數:a.字符串文件路徑;b.File對象。

該對象既可以對文件進行讀操作,也能進行寫操作,在進行對象實例化時可指定操作模式(r,rw)

注意:該對象在實例化時,如果要操作的文件不存在,會自動創建;如果文件存在,寫數據未指定位置,會從頭開始寫,即覆蓋原有的內容。可以用於多線程下載或多個線程同時寫數據到文件。

【案例】使用RandomAccessFile寫入文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
  * 使用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(); 
     }
}

Java IO流的高級概念

編碼問題

【案例 】取得本地的默認編碼

1
2
3
4
5
6
7
8
/**
  * 取得本地的默認編碼
  * */
publicclass CharSetDemo{
     public  static  void  main(String[] args){
         System.out.println( "系統默認編碼為:" + System.getProperty( "file.encoding" ));
     }
}

【案例 】亂碼的產生

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
}

對象的序列化

對象序列化就是把一個對象變為二進制數據流的一種方法。

一個類要想被序列化,就行必須實現java.io.Serializable接口。雖然這個接口中沒有任何方法,就如同之前的cloneable接口一樣。實現了這個接口之后,就表示這個類具有被序列化的能力。先讓我們實現一個具有序列化能力的類吧:

【案例 】實現具有序列化能力的類

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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;
}

【案例 】序列化一個對象 – ObjectOutputStream

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

【案例 】反序列化—ObjectInputStream

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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);
     }
}

注意:被Serializable接口聲明的類的對象的屬性都將被序列化,但是如果想自定義序列化的內容的時候,就需要實現Externalizable接口。

當一個類要使用Externalizable這個接口的時候,這個類中必須要有一個無參的構造函數,如果沒有的話,在構造的時候會產生異常,這是因為在反序列話的時候會默認調用無參的構造函數。

現在我們來演示一下序列化和反序列話:

【案例 】使用Externalizable來定制序列化和反序列化操作

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

注意:Serializable接口實現的操作其實是吧一個對象中的全部屬性進行序列化,當然也可以使用我們上使用是Externalizable接口以實現部分屬性的序列化,但是這樣的操作比較麻煩,

當我們使用Serializable接口實現序列化操作的時候,如果一個對象的某一個屬性不想被序列化保存下來,那么我們可以使用transient關鍵字進行說明:

【案例 】使用transient關鍵字定制序列化和反序列化操作

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

【運行結果】:

姓名:null 年齡:20

【案例 】序列化一組對象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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

參考文獻:

1、http://www.cnblogs.com/rollenholt/archive/2011/09/11/2173787.html

2、http://www.cnblogs.com/oubo/archive/2012/01/06/2394638.html

3、轉載自紅黑聯盟


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM