JAVA IO流詳解

一、流的概念和作用。

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

二、IO流的分類。

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

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

三、字符流和字節流。

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

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

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

(3)字節流操作的時候本身是不會用到緩衝區的,是對文件本身的直接操作。而字符流在操作的時候是會用到緩衝區的,通過緩衝區來操作文件。

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

四、輸入流和輸出流。

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

五、輸入字節流InputStream。

InputStream是所有輸入字節流的父類,它是一個抽象類。

ByteArrayInputStream、StringBufferInputStream、FileInputStream 是三種基本的介質流,它們分別從Byte 數組、StringBuffer、和本地文件中讀取數據。PipedInputStream 是從與其它線程共用的管道中讀取數據,與Piped 相關的知識後續單獨介紹。
ObjectInputStream 和所有FilterInputStream的子類都是裝飾流(裝飾器模式的主角)。意思是FileInputStream類可以通過一個String路徑名創建一個對象,FileInputStream(String name)。而DataInputStream必須裝飾一個類才能返回一個對象,DataInputStream(InputStream in)。

講解Demo。

讀取文件,節省空間。

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package javaio;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 字節流讀取文件內容
 * 節省空間的方式
 * @author xk
 */
public class IoTest {
    
    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.err.println("長度爲="+f.length());
        in.close();
        System.err.println(new String(b));
    }
    
}
逐一字節讀:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package javaio;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 逐字節讀
 * 讀取文件內容,節省空間
 * @author xk
 */
public class IoTest {
    
    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.err.println(new String(b));
    }
    
}
注意:上面的幾個例子都是在知道文件的內容多大,然後才展開的,有時候我們不知道文件有多大,這種情況下,我們需要判斷是否獨到文件的末尾。

字節流讀取文件:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package javaio;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 逐字節讀取文件內容
 * @author xk
 */
public class IoTest {
    
    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.err.println(new String(b));
    }
    
}
注意:當讀到文件末尾的時候會返回-1.正常情況下是不會返回-1的。

PushBackInputStream回退流操作:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaio;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.PushbackInputStream;

/**
 * @author xk
 */
public class IoTest {

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

        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);
            }
        }
    }
}
六、輸出字節流OutputStream。

OutputStream是所有輸出流的父類,它是一個抽象類。

ByteArrayOutputStream、FileOutputStream是兩種基本的介質流,它們分別向Byte 數組、和本地文件中寫入數據。PipedOutputStream 是向與其它線程共用的管道中寫入數據,
ObjectOutputStream 和所有FilterOutputStream的子類都是裝飾流。具體例子跟InputStream是對應的。

實例Demo:

向文件中寫入字符串:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaio;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 *
 * @author xk
 */
public class OutputStreamDemo {

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

        String fileName = "D:" + File.separator + "hello.txt";
        File f = new File(fileName);
        OutputStream os = new FileOutputStream(f);
        String str = "xukuntest";
        byte[] b = str.getBytes();
        os.write(b);
        os.close();
    }
}

/**
 * 字節流
 * 向文件中一個字節一個字節的寫入字符串
 * */
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();
    }
}

/**
 * 字節流
 * 向文件中追加新內容:
 * */
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();
    }
}

/**
 * 文件的複製
 * */
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();
    }
}

/**
 * 使用內存操作流將一個大寫字母轉化爲小寫字母
 * */
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);
    }
}

/**
 * 驗證管道流
 * */
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類示例
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();
    }
}
java.util.zip.ZipOutputStream

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類壓縮多個文件
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類展示

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());
    }
}
【案例】解壓縮文件(壓縮文件中只有一個文件的情況)

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類解壓縮一個壓縮文件中包含多個文件的情況

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();
       }
    }
}
七.幾個特殊的輸入流類分析
LineNumberInputStream
主要完成從流中讀取數據時,會得到相應的行號,至於什麼時候分行、在哪裏分行是由改類主動確定的,並不是在原始中有這樣一個行號。在輸出部分沒有對應的部分,我們完全可以自己建立一個LineNumberOutputStream,在最初寫入時會有一個基準的行號,以後每次遇到換行時會在下一行添加一個行號,看起來也是可以的。好像更不入流了。
PushbackInputStream
其功能是查看最後一個字節,不滿意就放入緩衝區。主要用在編譯器的語法、詞法分析部分。輸出部分的BufferedOutputStream 幾乎實現相近的功能。
StringBufferInputStream
已經被Deprecated,本身就不應該出現在InputStream部分,主要因爲String 應該屬於字符流的範圍。已經被廢棄了,當然輸出部分也沒有必要需要它了!還允許它存在只是爲了保持版本的向下兼容而已。
SequenceInputStream
可以認爲是一個工具類,將兩個或者多個輸入流當成一個輸入流依次讀取。完全可以從IO 包中去除,還完全不影響IO 包的結構,卻讓其更“純潔”――純潔的Decorator 模式。
【案例】將兩個文本文件合併爲另外一個文本文件
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進行格式化輸出

/**
 * 使用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向屏幕上輸出內容

/**
 * 使用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();
       }
    }
}
【案例】輸入輸出重定向

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.in重定向

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));
       }
    }
}
八.字符輸入流Reader
定義和說明:
在上面的繼承關係圖中可以看出:
Reader 是所有的輸入字符流的父類,它是一個抽象類。
CharReader、StringReader是兩種基本的介質流,它們分別將Char 數組、String中讀取數據。PipedReader 是從與其它線程共用的管道中讀取數據。
BufferedReader 很明顯就是一個裝飾器,它和其子類負責裝飾其它Reader 對象。
FilterReader 是所有自定義具體裝飾流的父類,其子類PushbackReader 對Reader 對象進行裝飾,會增加一個行號。
InputStreamReader 是一個連接字節流和字符流的橋樑,它將字節流轉變爲字符流。FileReader可以說是一個達到此功能、常用的工具類,在其源代碼中明顯使用了將FileInputStream 轉變爲Reader 的方法。我們可以從這個類中得到一定的技巧。Reader 中各個類的用途和使用方法基本和InputStream 中的類使用一致。後面會有Reader 與InputStream 的對應關係。
【案例】以循環方式從文件中讀取內容
/**
 * 字符流
 * 從文件中讀出內容
 * */
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));
下面是一個實例:

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類從文件中讀出內容

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);
    }
}
九.字符輸出流Writer
定義和說明:
在上面的關係圖中可以看出:
Writer 是所有的輸出字符流的父類,它是一個抽象類。
CharArrayWriter、StringWriter 是兩種基本的介質流,它們分別向Char 數組、String 中寫入數據。
PipedWriter 是向與其它線程共用的管道中寫入數據,
BufferedWriter 是一個裝飾器爲Writer 提供緩衝功能。
PrintWriter 和PrintStream 極其類似,功能和使用也非常相似。
OutputStreamWriter 是OutputStream 到Writer 轉換的橋樑,它的子類FileWriter 其實就是一個實現此功能的具體類(具體可以研究一SourceCode)。功能和使用和OutputStream 極其類似,後面會有它們的對應圖。
實例操作演示:
【案例】向文件中寫入數據
/**
 * 字符流
 * 寫入數據
 * */
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的內容就會換行了。
十.字符流與字節流轉換
轉換流的特點:
(1)其是字符流和字節流之間的橋樑
(2)可對讀取到的字節數據經過指定編碼轉換成字符
(3)可對讀取到的字符數據經過指定編碼轉換成字節
何時使用轉換流?
當字節和字符之間有轉換動作時;
流操作的數據需要編碼或解碼時。
具體的對象體現:
InputStreamReader:字節到字符的橋樑
OutputStreamWriter:字符到字節的橋樑
這兩個流對象是字符體系中的成員,它們有轉換作用,本身又是字符流,所以在構造的時候需要傳入字節流對象進來。
字節流和字符流轉換實例:
【案例】將字節輸出流轉化爲字符輸出流
/**
 * 將字節輸出流轉化爲字符輸出流
 * */
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();
    }
}
【案例】將字節輸入流轉換爲字符輸入流

/**
 * 將字節輸入流變爲字符輸入流
 * */
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();
    }
}
十一.File類
File類是對文件系統中文件以及文件夾進行封裝的對象,可以通過對象的思想來操作文件和文件夾。 File類保存文件或目錄的各種元數據信息,包括文件名、文件長度、最後修改時間、是否可讀、獲取當前文件的路徑名,判斷指定文件是否存在、獲得當前目錄中的文件列表,創建、刪除文件和目錄等方法。

【案例 】創建一個文件

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類的兩個常量

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的代碼:

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】刪除一個文件(或者文件夾)

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】創建一個文件夾

/**
 * 創建一個文件夾
 * */
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】列出目錄下的所有文件

/**
 * 使用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]);
       }
    }
}
【案例7】遞歸搜索指定目錄的全部內容,包括文件和文件夾
* 列出指定目錄的全部內容
 * */
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; i++)="" {="" 遞歸調用="" print(filearray[i]);="" }="" else{="" system.out.println(f);="" }<="" pre="">
<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="brush: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="brush: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="brush: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="brush: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="brush: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="brush: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="brush: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="brush: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="brush: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; ++i){="" student="" s="(Student)" obj[i];="" system.out.println(s);="" }="" 序列化="" public="" static="" voidser(object[]="" obj)="" throws="" exception{="" file="" +="" file.separator="" "hello.txt");="" objectoutputstream="" out="new" objectoutputstream(new="" fileoutputstream(="" file));="" out.writeobject(obj);="" out.close();="" 反序列化="" object[]dser()="" objectinputstreaminput="new" objectinputstream(new="" fileinputstream(="" object[]="" obj="(Object[])" input.readobject();="" input.close();="" return="" obj;="" class="" implements="" serializable{="" student(){="" student(stringname,="" int="" age){="" this.name="name;" this.age="age;" @override="" string="" tostring(){="" "姓名:="" "="" name="" 年齡:"="" age;="" private="" name;="" }<="" pre="">
<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;>









發佈了28 篇原創文章 · 獲贊 5 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章