更多 Java IO & NIO方面的文章,請(qǐng)參見(jiàn)文集《Java IO & NIO》
FileInputStream & FileOutputStream
讀寫(xiě)格式:按字節(jié)讀寫(xiě),每次讀寫(xiě)一個(gè)字節(jié),或者讀寫(xiě)一個(gè)字節(jié)數(shù)組。
public static void main(String[] args) throws Exception {
InputStream fin = new FileInputStream("a.txt");
OutputStream fout = new FileOutputStream("b.txt");
System.out.println("How many bytes? = " + fin.available());
int c;
while((c = fin.read()) != -1) {
System.out.print((char) c);
fout.write(c);
}
}
輸出:
How many bytes? = 12
Hello
World
使用緩沖流 BufferedInputStream & BufferedOutputStream
讀寫(xiě)格式:按字節(jié)讀寫(xiě),每次讀寫(xiě)一個(gè)字節(jié),或者讀寫(xiě)一個(gè)字節(jié)數(shù)組。
優(yōu)勢(shì):使用緩沖流,更節(jié)省時(shí)間,減少訪問(wèn)磁盤的數(shù)目
緩沖區(qū)默認(rèn)大小為 8M:private static int DEFAULT_BUFFER_SIZE = 8192;
public static void main(String[] args) throws Exception {
InputStream fin = new FileInputStream("a.txt");
BufferedInputStream bin = new BufferedInputStream(fin);
OutputStream fout = new FileOutputStream("b.txt");
BufferedOutputStream bout = new BufferedOutputStream(fout);
System.out.println("How many bytes? = " + bin.available());
// Read and Write by byte
int c;
while ((c = bin.read()) != -1) {
System.out.print((char) c);
bout.write(c);
}
// Read and Write by byte array
byte[] buf = new byte[12];
while (bin.read(buf) != -1) {
for(byte b: buf)
System.out.print((char) b);
bout.write(buf);
}
}
輸出:
How many bytes? = 12
Hello
World
FileInputStream VS BufferredInputStream
對(duì)比以上兩個(gè)例子:
一個(gè)使用 FileInputStream 來(lái)操作文件
另外一個(gè)使用 BufferredInputStream 來(lái)封裝 FileInputStream,然后操作文件。效率更高?。。?/strong>
原因分析:
FileInputStream 的 read 方法實(shí)現(xiàn)如下:
可以看出,實(shí)際上調(diào)用了一個(gè)本地方法,每次讀取一個(gè)字節(jié),都需要通過(guò) OS 來(lái)訪問(wèn)磁盤。
/**
* Reads a byte of data from this input stream. This method blocks
* if no input is yet available.
*
* @return the next byte of data, or <code>-1</code> if the end of the
* file is reached.
* @exception IOException if an I/O error occurs.
*/
public int read() throws IOException {
return read0();
}
private native int read0() throws IOException;
BufferedInputStream 的 read 方法實(shí)現(xiàn)如下:
可以看出,BufferedInputStream 有一個(gè)緩沖區(qū),每次從磁盤中讀取 8M 的字節(jié),存儲(chǔ)到內(nèi)存緩沖區(qū)中,調(diào)用 read() 時(shí)實(shí)際上是讀取緩沖區(qū),無(wú)需訪問(wèn)磁盤。
public synchronized int read() throws IOException {
if (pos >= count) {
fill();
if (pos >= count)
return -1;
}
return getBufIfOpen()[pos++] & 0xff;
}
讀取具體數(shù)據(jù)類型 DateInputStream & DateOutputStream
讀寫(xiě)格式:按字節(jié)讀寫(xiě),按照具體的數(shù)據(jù)類型讀寫(xiě)特定數(shù)目的字節(jié):
- readChar, writeChar:每次讀寫(xiě) 2 個(gè)字節(jié)
public final char readChar() throws IOException {
int ch1 = in.read();
int ch2 = in.read();
if ((ch1 | ch2) < 0)
throw new EOFException();
return (char)((ch1 << 8) + (ch2 << 0));
}
public final void writeChar(int v) throws IOException {
out.write((v >>> 8) & 0xFF);
out.write((v >>> 0) & 0xFF);
incCount(2);
}
- readInt, writeInt:每次讀寫(xiě) 4 個(gè)字節(jié)
public final int readInt() throws IOException {
int ch1 = in.read();
int ch2 = in.read();
int ch3 = in.read();
int ch4 = in.read();
if ((ch1 | ch2 | ch3 | ch4) < 0)
throw new EOFException();
return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));
}
public final void writeInt(int v) throws IOException {
out.write((v >>> 24) & 0xFF);
out.write((v >>> 16) & 0xFF);
out.write((v >>> 8) & 0xFF);
out.write((v >>> 0) & 0xFF);
incCount(4);
}
- readDouble, writeDouble:每次讀寫(xiě) 8 個(gè)字節(jié)
- readLong, writeLong:每次讀寫(xiě) 8 個(gè)字節(jié)
- ...
DateInputStream & DateOutputStream 的使用:
public static void main(String[] args) throws Exception {
OutputStream fout = new FileOutputStream("chars.txt");
DataOutputStream dout = new DataOutputStream(fout);
char chars[] = {'A', 'B', 'C', 'D'};
for (int c : chars) {
dout.writeChar(c);
}
dout.flush();
InputStream fin = new FileInputStream("chars.txt");
DataInputStream din = new DataInputStream(fin);
char c;
while (din.available() > 0) {
c = din.readChar();
System.out.print(c);
}
}
輸出:
ABCD
注意事項(xiàng):
如下代碼會(huì)將 1 按照二進(jìn)制形式寫(xiě)入文件中,占據(jù) 4 bytes。
因此用記事本打開(kāi)該文本文件,其實(shí)無(wú)法看到數(shù)字 1。
int i = 1;
dout.writeInt(i);
讀取對(duì)象 ObjectInputStream & ObjectOutputStream
讀寫(xiě)格式:按字節(jié)讀寫(xiě),讀寫(xiě)的對(duì)象需要實(shí)現(xiàn) Serializable 接口。
ObjectInputStream & ObjectOutputStream 的使用:
public class Stream_Object_Test {
public static void main(String[] args) throws Exception {
OutputStream fout = new FileOutputStream("people.txt");
ObjectOutputStream oout = new ObjectOutputStream(fout);
People p = new People("Tom", 20);
oout.writeObject(p);
InputStream fin = new FileInputStream("people.txt");
ObjectInputStream oin = new ObjectInputStream(fin);
People new_p = (People) oin.readObject();
System.out.println(new_p.getName() + " " + new_p.getAge());
}
}
class People implements Serializable {
private String name;
private int age;
People(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}