Java IO 對字符的讀取和寫出

1、對字符的讀取

只能讀取純文本,不能讀取二進制文件如音頻,視頻等,doc文件以及其他不是純文本的文檔。

1.1 純文本的讀取

使用java.io.Reader類讀取純文本文件,其源代碼重要的幾個方法如下:

package java.io;
public abstract class Reader implements Readable, Closeable {
    /**
     * 讀取一個字符
     */
    public int read() throws IOException {
        char cb[] = new char[1];
        if (read(cb, 0, 1) == -1)
            return -1;
        else
            return cb[0];
    }
    /**
     * 讀取一個字符數組
     */
    public int read(char cbuf[]) throws IOException {
        return read(cbuf, 0, cbuf.length);
    }
    /**
     * 讀取一個字符數組或者字符數組的一部分
     */
    abstract public int read(char cbuf[], int off, int len) throws IOException;
    /**
     * 關閉流
     */
     abstract public void close() throws IOException;
}

1.2 讀取純文本的demo如下:

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

2、對字符的寫出

只能對純文本寫出。

2.1 純文本的寫出

使用java.io.Writer類向純文本進行寫出,其中源碼幾個重要的方法如下:

package java.io;
public abstract class Writer implements Appendable, Closeable, Flushable {
    /**
     * 寫一個字符
     */
    public void write(int c) throws IOException {
        synchronized (lock) {
            if (writeBuffer == null){
                writeBuffer = new char[WRITE_BUFFER_SIZE];
            }
            writeBuffer[0] = (char) c;
            write(writeBuffer, 0, 1);
        }
    }
    /**
     * 寫一個字符數組
     */
    public void write(char cbuf[]) throws IOException {
        write(cbuf, 0, cbuf.length);
    }
    /**
     *寫一個字符數組或字符數組的一部分
     */
    abstract public void write(char cbuf[], int off, int len) throws IOException;

    /**
     * 寫一個字符串
     */
    public void write(String str) throws IOException {
        write(str, 0, str.length());
    }
    /**
     * 寫一個字符串或字符串的一部分
     */
    public void write(String str, int off, int len) throws IOException {
        synchronized (lock) {
            char cbuf[];
            if (len <= WRITE_BUFFER_SIZE) {
                if (writeBuffer == null) {
                    writeBuffer = new char[WRITE_BUFFER_SIZE];
                }
                cbuf = writeBuffer;
            } else {    // Don't permanently allocate very large buffers.
                cbuf = new char[len];
            }
            str.getChars(off, (off + len), cbuf, 0);
            write(cbuf, 0, len);
        }
    }
    /**
     * 追加特定字符到此流中
     */
    public Writer append(CharSequence csq) throws IOException {
        if (csq == null)
            write("null");
        else
            write(csq.toString());
        return this;
    }
    /**
     * 追加特定字符或特定字符的一部分到此流中
     */
    public Writer append(CharSequence csq, int start, int end) throws IOException {
        CharSequence cs = (csq == null ? "null" : csq);
        write(cs.subSequence(start, end).toString());
        return this;
    }
    /**
     * 追加特定字符到此流中
     */
    public Writer append(char c) throws IOException {
        write(c);
        return this;
    }
    /**
     * 刷新流
     */
    abstract public void flush() throws IOException;
    /**
     * 關閉流
     */
    abstract public void close() throws IOException;
}

2.2 純文本寫出demo如下:

/**
 * jdk 7 新特性
 * 
 * @param file
 *            指定輸出文件
 * @param msg
 *            輸出內容
 * @param append
 *            是否追加,true 追加 false 不追加
 */
public static void writeToFileWithJdk7(File file, String msg, boolean append) {
    try (Writer writer = new FileWriter(file)) {
        writer.write(msg);
        writer.flush();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
/**
 * 
 * @param file
 *            指定輸出文件
 * @param msg
 *            輸出內容
 * @param append
 *            是否追加,true 追加 false 不追加
 */
public static void writeToFile(File file, String msg, boolean append) {
    Writer writer = null;
    try {
        writer = new FileWriter(file);
        writer.write(msg);
        writer.flush();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (null != writer) {
                writer.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
/**
 * 
 * @param filePath
 *            指定輸出文件路徑
 * @param msg
 *            輸出內容
 * @param append
 *            是否追加,true 追加 false 不追加
 */
public static void writeToFile(String filePath, String msg, boolean append) {
    writeToFile(new File(filePath), msg, append);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章