Java IO 對字節的讀取和寫出

1 字節的讀取

對於字節流的輸入,可以分爲網絡上的字節如文件下載,以及文件如讀取文件。

1.1 文件的讀取
使用java.io.FileInputStream類來進行對文件的讀取,以下是源碼中幾個重要的方法

package java.io;

public class FileInputStream extends InputStream {

    /**
     *  根據文件絕對路徑構造次對象
     */
    public FileInputStream(String name) throws FileNotFoundException {
        this(name != null ? new File(name) : null);
    }

    /**
     * 根據文件構造次對象
     */
    public FileInputStream(File file) throws FileNotFoundException {
        String name = (file != null ? file.getPath() : null);
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkRead(name);
        }
        if (name == null) {
            throw new NullPointerException();
        }
        if (file.isInvalid()) {
            throw new FileNotFoundException("Invalid file path");
        }
        fd = new FileDescriptor();
        fd.attach(this);
        path = name;
        open(name);
    }

    /**
     * 讀取一個字節數據
     */
    public int read() throws IOException {
        return read0();
    }

    /**
     * 讀取一個字節數組數據
     */
    public int read(byte b[]) throws IOException {
        return readBytes(b, 0, b.length);
    }

    /**
     * 根據指定長度讀取一個字節數組數據
     */
    public int read(byte b[], int off, int len) throws IOException {
        return readBytes(b, off, len);
    }

    /**
     * 跳過指定的字節數據後開始讀取
     */
    public native long skip(long n) throws IOException;

    /**
     * 返回可讀取的數據大小
     */
    public native int available() throws IOException;

    /**
     * 關閉流,釋放資源
     */
    public void close() throws IOException {
        synchronized (closeLock) {
            if (closed) {
                return;
            }
            closed = true;
        }
        if (channel != null) {
           channel.close();
        }

        fd.closeAll(new Closeable() {
            public void close() throws IOException {
               close0();
           }
        });
    }
}

1.2 讀取文件的demo例子如下:

/**
 * @param file 文件對象
 */
public static void readFile(File file) {
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(file);
        byte[] buffer = new byte[1024 * 1024 * 10];
        int len = 0;
        while (-1 != (len = fis.read(buffer))) {
            System.out.println(new String(buffer, 0, len));
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (null != fis) {
                fis.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

/**
 * @param filePath 文件路徑
 */
public static void readFile(String filePath) {
    readFile(new File(filePath));
}

/**
 * 
 * @param file
 *            文件對象
 */
public static void readFile(File file) {
    // java 7 新特性 try-with-resource
    // 不用手動釋放資源,程序自動釋放,因爲FileInputStream實現了AutoCloseable接口
    try (FileInputStream fis = new FileInputStream(file)) {
        byte[] buffer = new byte[1024 * 1024 * 10];
        int len = 0;
        while (-1 != (len = fis.read(buffer))) {
            System.out.println(new String(buffer, 0, len));
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

2 字節的寫出

對於字節流的輸出,可以分爲相應網絡請求,以及文件如輸出到文件。

2.1 文件的寫出
使用java.io.FileOutputStream類來進行對文件的寫出操作。以下是源碼中比較重要的幾個方法:

package java.io;

public class FileOutputStream extends OutputStream {

    /**
     * 創建一個文件輸出流,輸出到指定文件
     */
    public FileOutputStream(String name) throws FileNotFoundException {
        this(name != null ? new File(name) : null, false);
    }

    /**
     * 創建一個文件輸出流,輸出到指定文件
     * 如果第二個參數爲true,則從此文件末尾開始輸出而不是文件頭部開始
     */
    public FileOutputStream(String name, boolean append)
        throws FileNotFoundException
    {
        this(name != null ? new File(name) : null, append);
    }

    /**
     * 創建一個文件輸出流,輸出到指定文件
     */
    public FileOutputStream(File file) throws FileNotFoundException {
        this(file, false);
    }

    /**
     * 創建一個文件輸出流,輸出到指定文件
     * 如果第二個參數爲true,則從此文件末尾開始輸出而不是文件頭部開始
     */
    public FileOutputStream(File file, boolean append)
        throws FileNotFoundException
    {
        String name = (file != null ? file.getPath() : null);
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkWrite(name);
        }
        if (name == null) {
            throw new NullPointerException();
        }
        if (file.isInvalid()) {
            throw new FileNotFoundException("Invalid file path");
        }
        this.fd = new FileDescriptor();
        fd.attach(this);
        this.append = append;
        this.path = name;

        open(name, append);
    }

    /**
     * 寫一個字節到流中,append爲true時,寫到此文件的末尾
     */
    private native void write(int b, boolean append) throws IOException;

    /**
     * 寫一個字節到流中
     */
    public void write(int b) throws IOException {
        write(b, append);
    }

    /**
     * 寫一個字節數組或字節數組的一部分到流中
     * append爲true時,寫到此文件的末尾
     */
    private native void writeBytes(byte b[], int off, int len, boolean append)
        throws IOException;

    /**
     * 寫一個字節數組到流中
     */
    public void write(byte b[]) throws IOException {
        writeBytes(b, 0, b.length, append);
    }

    /**
     * 寫一個字節數組或字節數組的一部分到流中
     */
    public void write(byte b[], int off, int len) throws IOException {
        writeBytes(b, off, len, append);
    }

    /**
     * 關閉流,釋放資源
     */
    public void close() throws IOException {
        synchronized (closeLock) {
            if (closed) {
                return;
            }
            closed = true;
        }

        if (channel != null) {
            channel.close();
        }

        fd.closeAll(new Closeable() {
            public void close() throws IOException {
               close0();
           }
        });
    }
}

2.2 文件輸出流的Demo例子如下:

/**
 * 
 * @param file 指定輸出文件
 * @param msg 輸出內容
 * @param append 是否追加,true 追加 false 不追加
 */
private static void writeToFile(File file, String msg, boolean append) {
    FileOutputStream bos = null;
    try {
        bos = new FileOutputStream(file);
        bos.write(msg.getBytes(), 0, msg.getBytes().length);
        bos.flush();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (null != bos) {
                bos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

/**
 * 
 * @param filePath 指定輸出文件路徑
 * @param msg 輸出內容
 * @param append 是否追加,true 追加 false 不追加
 */
private static void writeToFile(String filePath, String msg, boolean append) {
    writeToFile(new File(filePath), msg, append);
}

/**
* jdk 7 新特性(與FileInputStream一致)
 * @param file 指定輸出文件
 * @param msg 輸出內容
 * @param append 是否追加,true 追加 false 不追加
 */
private static void writeToFile(File file, String msg, boolean append) {
    try (FileOutputStream bos = new FileOutputStream(file)){
        bos.write(msg.getBytes(), 0, msg.getBytes().length);
        bos.flush();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
發佈了40 篇原創文章 · 獲贊 11 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章