聲明:本系列只供本人自學(xué)使用,勿噴誊役。
當(dāng)你需要從輸入流中讀取基本數(shù)據(jù)類型虑稼,或者往輸出流中寫(xiě)入基本數(shù)據(jù)類型,就需要用DataInputStream或DataOutputStream來(lái)裝飾流势木。
一、DataInputStream
public class DataInputStream extends FilterInputStream implements DataInput{
public DataInputStream(InputStream in) {
super(in);
}
}
- 核心方法【DataInput接口的方法】
讀取某類型歌懒,就連續(xù)read() n次(n=該類型占用字節(jié)數(shù))
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 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));
}
二啦桌、DataInputStream
public class DataOutputStream extends FilterOutputStream implements DataOutput {
public DataOutputStream(OutputStream out) {
super(out);
}
}
- 核心方法【DataOutput接口的方法】
寫(xiě)入某類型,就連續(xù)write() n次(n=該類型占用字節(jié)數(shù))
public final void writeChar(int v) throws IOException {
out.write((v >>> 8) & 0xFF);
out.write((v >>> 0) & 0xFF);
incCount(2);
}
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);
}