Java IO學習筆記+代碼(3)

字符流處理
/*
 * ProcesserCharacterStream.java
 *
 * Created on 2006年8月23日, 上午8:02
 *
 * 字符流處理
 *
 * java.io包中加入了專門用於字符流處理的類,這些類都是Reader和Writer類的子類,
 * Reader和Writer是兩個抽象類,只提供了一系列用於字符流處理的接口,不能生成這
 * 兩個類的實例。
 * java.io包中用於字符流處理的最基本的類是InputStreamReader和OutputStreamWriter,
 * 用來在字節流和字符流之間作爲中介。
 *
 * 下面是InputStreamReader類和OutputStreamWriter類的常用方法:
 *
* public InputStreamReader(InputStream in)
 * 根據當前平臺缺省的編碼規範,基於字節流in生成一個輸入字符流。
* public InputStreamReader(InputStream in, String sysCode)throws UnSupportedEncodingException
 * 按照參數sysCode指定的編碼規範,基於字節流in構造輸入字符流,如果不支持參數sysCode中指定的編碼規範,就會產生異常。
* public OutputStreamWriter(OutputStream out)
 * 根據當前平臺缺省的編碼規範,基於字節流out生成一個輸入字符流。
* public OutputStreamWriter(OutputStream out, String sysCode) throws UnsupportedEncodingException
 * 按照參數sysCode指定的編碼規範,基於字節流out構造輸入字符流,如果不支持參數sysCode中指定的編碼規範,就會產生異常。
* public String getEncoding()
 * 獲得當前字符流使用的編碼方式。
* public void close() throws IOException
 * 用於關閉流。
* public int read() throws IOException
 * 用於讀取一個字符。
* public int read(char[] cbuf, int off, int len)
 * 用於讀取len個字符到數組cbuf的索引off處。
* public void write(char[] cbuf, int off, int len) throws IOException
 * 將字符數組cbuf中從索引off處開始的len個字符寫入輸出流。
* public void write(int c) throws IOException
 * 將單個字符寫入輸入流。
* public void write(String str, int off, int len) throws IOException
 * 將字符串str中從索引off位置開始的ltn個字符寫入輸出流。
 *
 * 此外,爲了提高字符流處理的效率,在Java語言中,引入了BufferedReader和BufferWriter類,這兩個類對字符流進行塊處理。
 * 兩個類的常用方法如下:
 * public BufferedReader(Reader in)
 * 用於基於普通字符輸入流in生成相應的緩衝流。
 * public BufferedReader(Reader in, int bufSize)
 * 用於基於普通字符輸入流in生成相應的緩衝流,緩衝區大小爲參數bufSize指定。
 * public BufferedWriter(Writer out)
 * 用於基於普通字符輸入流out生成相應的緩衝流。
 * public BufferedWriter(Writer out, int bufSize)
 * 用於基於普通字符輸入流out生在相應緩衝流,緩衝流大小爲參數bufSize指定。
 * public String readLine() throws IOException
 * 用於從輸入流中讀取一行字符。
 * public void newLine() throws IOException
 * 用於向字符輸入流中寫入一行結束標記,值得注意的是,該標記不是簡單的換行符"\n",而是系統定義的屬性line.separator。
 */
package study.iostudy;
import java.io.*;
public class ProcesserCharacterStream
{
    public static void main(String[] args)
            throws FileNotFoundException, IOException
    {
        String lineStr;
        FileInputStream fileInStream;
        InputStreamReader inputReader;
        BufferedReader bufReader;
        FileOutputStream fileOutStream;
        OutputStreamWriter outputWriter;
        BufferedWriter bufWriter;
        fileInStream = new FileInputStream("d:\\mydir\\secondFile.txt");
        inputReader = new InputStreamReader(fileInStream);
        bufReader = new BufferedReader(inputReader);
        System.out.println("------------------------------------------------");
        System.out.println("There are file content before modify:");
        while ((lineStr = bufReader.readLine()) != null)
            System.out.println(lineStr);
        bufReader.close();
        inputReader.close();
        fileInStream.close();
        fileOutStream = new FileOutputStream("d:\\mydir\\secondFile.txt");
        outputWriter = new OutputStreamWriter(fileOutStream);
        bufWriter = new BufferedWriter(outputWriter);
        String newStr = new String("Modify the file ! \r\nThis is a nice thing. \r\nWe can write anything.");
        bufWriter.write(newStr, 0, newStr.length());
        System.out.println(newStr);
        bufWriter.close();
        outputWriter.close();
        fileOutStream.close();
        fileInStream = new FileInputStream("d:\\mydir\\secondFile.txt");
        inputReader = new InputStreamReader(fileInStream);
        bufReader = new BufferedReader(inputReader);
        System.out.println("------------------------------------------------");
        System.out.println("There are file content after modify:");
        while ((lineStr = bufReader.readLine()) != null)
            System.out.println(lineStr);
        bufReader.close();
        inputReader.close();
        fileInStream.close();
    }
}
 
接收鍵盤輸入數據
/*
 * OutputKeyPress.java
 *
 * Created on 2006年8月23日, 上午9:27
 *
 * 接收鍵盤輸入數據
 */
package study.iostudy;
import java.io.*;
public class OutputKeyPress
{
    public static void main(String[] args)
    {
        System.out.println("This is a example about acceptance of keyboard.");
        String tempStr = "0";
        try
        {
            InputStreamReader inputReader;
            BufferedReader bufReader;
            inputReader = new InputStreamReader(System.in);
            bufReader = new BufferedReader(inputReader);
            tempStr = bufReader.readLine();
            System.out.println("Input num is: " + tempStr);
        }catch(IOException e)
        {
            e.printStackTrace();
        }
        int n = Integer.parseInt(tempStr);
        int nultiNum = 1;
        for (int i =1; i <= n; i++)
        {
            nultiNum *= i;
        }
        System.out.println("multiply of input number is: " + nultiNum);
    }   
}
 
過濾流
/*
 * FilterStream.java
 *
 * Created on 2006年8月23日, 上午9:40
 *
 * 過濾流
 *
 * 過濾流在讀/寫數據的同時可以對數據進行處理,並提供了同步機制,
 * 這樣在同一時刻只有一個線程可以訪問一個I/O流。在java.io包中,
 * FilterInputStream和FilterOutputStream類是所有過濾輸入流和
 * 輸出流的父類,它們是抽象類,本身不能生成任何實例,在這兩上類
 * 之下,分別實現了幾物特殊的過濾輸入流和輸出流,利用這些特殊輸
 * 入流和輸出流的實例可以進行流處理。
 *
 * 下面介紹幾個過濾輸入流和輸出流的子類:
 *
 * BufferedInputStream 和 BufferedOutputStream
 * 這兩個類實現了帶緩衝的過濾流,將任意的輸入流和輸出流綁定到緩
 * 沖流上就會提高性能。
 * 對於BufferedInputStream類,當系統讀取數據時,數據按塊讀入緩
 * 衝區,隨後讀操作直接訪問緩衝區。使用BufferedOutputStream進行
 * 輸出時,數據首先寫入緩衝區,當緩衝區滿時,緩衝區中的數據寫入
 * 連接的輸出流,BufferedOutputStream類提供的方法flush()可以強
 * 制將緩衝區的內容全部寫入輸出流。
 *
 * DataInputStream 和 DataOutputStream
 * 這兩個類不僅能讀寫數據流,而且能讀寫各種各樣的Java語言本身固
 * 有的數據類型,如int、float等。
 *
 * PushbackInputStream
 * PushbackInputStream類提供了方法將剛讀過的字節退回到輸入流中,
 * 後面的內容就可以用到該字節。
 */
 
package study.iostudy;
import java.io.*;
public class FilterStream
{
    public static void main(String[] args)
    {
        try
        {
            FileInputStream inStream;
            FileOutputStream outStream;
            BufferedInputStream bufInObj;
            BufferedOutputStream bufOutObj;
            DataInputStream dataInObj;
            PushbackInputStream pushObj;
            byte[] tempBuf = new byte[1024];
            int copyLen;
            inStream = new FileInputStream("d:\\mydir\\secondFile.txt");
            outStream = new FileOutputStream("d:\\mydir\\thirdFile.txt");
            bufInObj = new BufferedInputStream(inStream);
            bufOutObj = new BufferedOutputStream(outStream);
            dataInObj = new DataInputStream(inStream);
            System.out.println(dataInObj.readBoolean());
            while ((copyLen = bufInObj.read(tempBuf, 0, 1024)) != -1)
            {
                String copyStr = new String(tempBuf);
                System.out.println(copyStr);
                bufOutObj.write(tempBuf, 0, copyLen);
                bufOutObj.flush();
            }
            int pushData;
            byte[] pushByte = {'o', 'k'};
            pushObj = new PushbackInputStream(
                    new FileInputStream("d:\\mydir\\thirdFile.txt"), 1000);
            while ((pushData = pushObj.read()) != -1)
            {
                if (Character.isLetter((char)pushData))
                {
                    System.out.print((char)pushData);
                }
                else
                {
                    System.out.println();
                    pushObj.unread(pushByte);
                }
            }
        }catch(FileNotFoundException e)
        {
            System.out.println("File not found or persission denied.");
        }catch(IOException e)
        {
            System.out.println("error:" + e);
        }
    }
    /*
     * 在上面的程序中,我們首先聲明瞭FileInputStream類對象inStream和
     * FileOutputStream類的對象outStream,接着聲明瞭BufferInputStream
     * 類對象bufObj、BufferedOutputStream類對象bufOutObj、
     * DataInputStream類對象dataInObj以及PushbackInputStream類對象pushObj,
     * 在try代碼塊中對上面這些對象進行初始化,程序的目的是通過BufferedInputStream
     * 類對象bufInObj和BufferedOutputStream類對象bufOutObj將secondFile.txt
     * 文件中內容輸出到屏幕,並將該文件的內容寫入thirdFile.txt文件中,值得注意的是,
     * 將secondFile.txt文件中的內容輸出之前,程序中使用
     * "System.out.println(dataInObj.readBoolean());" 語句根據readBoolean()結果
     * 輸出了true,而secondFile.txt文件開始內容爲“Modify”,和一個字符爲M,
     * 因此輸出的文件內容沒有“M”字符,thirdFile.txt文件中也比secondFile.txt
     * 文件少第一個字符“M”。隨後,通過PushbackInputStream類對象pushObj讀取
     * thirdFile.txt文件中的內容,輸出讀到的字符,當讀到的不是字符,輸出回車,將字符
     * 數組pushByte寫回到thirdFile.txt文件中,也就是“ok”寫回文件中。
     */
 
}
 
順序輸入流
/*
 * SequenceStream.java
 *
 * Created on 2006年8月23日, 上午10:55
 *
 * 順序輸入流
 *
 * java.io包中提供了SequenceInputStream類,用於將多個輸入流順序連接起來,
 * 使它們看起來就像一個較長的流。
 */
package study.iostudy;
import java.io.*;
public class SequenceStream
{
    public static void main(String[] args)
    {
        FileInputStream fileStream1, fileStream2;
        try
        {
            String allStr;
            fileStream1 = new FileInputStream("d:\\mydir\\secondFile.txt");
            fileStream2 = new FileInputStream("d:\\mydir\\thirdFile.txt");
            SequenceInputStream seqStream = new SequenceInputStream(
                    fileStream1, fileStream2);
            BufferedInputStream bufObj = new BufferedInputStream(seqStream);
            byte[] bufByte = new byte[1024];
            while (bufObj.read(bufByte, 0, 1024) != -1)
            {
                String tempStr = new String(bufByte);
                System.out.println(tempStr);
            }
        }catch(FileNotFoundException e)
        {
            System.out.println("File not found or no permission.");
        }catch(IOException e)
        {
            System.out.println("error:" + e);
        }
    }
}
 
對象串行化
 
/*
 * SerializableObject.java
 *
 * Created on 2006年8月23日, 上午11:26
 *
 * 對象串行化
 *   對象通過寫出描述自己狀態的數值來記錄自己,這個過程叫做對象串行化。對象的壽命通
 * 常是隨着生成該對象的程序的終止而終止,在有些情況下,需要將對象的狀態保存下來,然後
 * 在必要的時候將對象恢復,值得注意的是,如果變量是另一個對象的引用,則引用的對象也要
 * 串行化,串行化是一個遞歸的過程,可能會涉及到一個複雜樹結構的串行化,比如包括原有對
 * 象,對象的對象等。
 *   在java.io包中,接口Serializable是實現對象串行化的工具,只有實現了Serializable
 * 的對象纔可以被串行化。Serializable接口中沒有任何的方法,當一個類聲明實現Seriali-
 * zable接口時,只是表明該類遵循串行化協議,而不需要實現任何特殊的方法。
 *   在進行對象串行化時,需要注意將串行化的對象和輸入、輸出流聯繫起來,首先通過對
 * 象輸出流將對象狀態保存下來,然後通過對象輸入流將對象狀態恢復。
 */
 
package study.iostudy;
 
import java.io.*;
 
class Book implements Serializable
{
    String isbn;
    String name;
    int page;
    String type;
    public Book(String isbn, String name, int page, String type)
    {
        this.isbn = isbn;
        this.name = name;
        this.page = page;
        this.type = type;
    }
}
 
public class SerializableObject implements Serializable
{
    public static void main(String[] args)
            throws IOException, ClassNotFoundException
    {
        Book bookObj = new Book("7-02-016450-1", "Java", 218, "programming");
        FileOutputStream fileOStream = new FileOutputStream("temp.ser");
        ObjectOutputStream objOutStream = new ObjectOutputStream(fileOStream);
        try
        {
            objOutStream.writeObject(bookObj);
            objOutStream.close();
        }catch(IOException e)
        {
            e.printStackTrace();
        }
        bookObj = null;
        FileInputStream fileInStream = new FileInputStream("temp.ser");
        ObjectInputStream objInStream = new ObjectInputStream(fileInStream);
        try
        {
            bookObj = (Book)objInStream.readObject();
            objInStream.close();
        }catch(IOException e)
        {
            e.printStackTrace();
        }
        System.out.println("------------------------------------------------");
        System.out.println("There are information about book:");
        System.out.println("ISBN Number: " + bookObj.isbn);
        System.out.println("Book Name: " + bookObj.name);
        System.out.println("Book Page: " + bookObj.page);
        System.out.println("Book Type: " + bookObj.type);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章