Step By Step(Java 网络篇) (六)

2014-11-24 03:03:08 · 作者: · 浏览: 14
s(v));
54 }
55 public final void writeFloat(float v) throws IOException {
56 writeInt(Float.floatToIntBits(v));
57 }
58 //short、int和long都是多字节的,因此就都需要翻转了。
59 public final void writeInt(int v) throws IOException {
60 work[0] = (byte) v;
61 work[1] = (byte) (v >> 8);
62 work[2] = (byte) (v >> 16);
63 work[3] = (byte) (v >> 24);
64 dout.write(work, 0, 4);
65 }
66 public final void writeLong(long v) throws IOException {
67 work[0] = (byte) v;
68 work[1] = (byte) (v >> 8);
69 work[2] = (byte) (v >> 16);
70 work[3] = (byte) (v >> 24);
71 work[4] = (byte) (v >> 32);
72 work[5] = (byte) (v >> 40);
73 work[6] = (byte) (v >> 48);
74 work[7] = (byte) (v >> 56);
75 dout.write(work, 0, 8);
76 }
77 public final void writeShort(int v) throws IOException {
78 work[0] = (byte) v;
79 work[1] = (byte) (v >> 8);
80 dout.write(work, 0, 2);
81 }
82 public final void writeUTF(String s) throws IOException {
83 dout.writeUTF(s);
84 }
85 }
2) 小端数据输入流:
输入流的实现和输出流的实现在基本概念和应用技巧上是完全一样的,这里就不再给出更多的注释了。
1 public class LEDataInputStream implements DataInput {
2 protected final DataInputStream din;
3 protected final InputStream is;
4 protected final byte[] work;
5 public static String readUTF(DataInput in) throws IOException {
6 return DataInputStream.readUTF(in);
7 }
8 public LEDataInputStream(InputStream in) {
9 is = in;
10 din = new DataInputStream(in);
11 work = new byte[8];
12 }
13 public final void close() throws IOException {
14 din.close();
15 }
16 public final int read(byte ba[], int off, int len) throws IOException {
17 return is.read(ba, off, len);
18 }
19 public final boolean readBoolean() throws IOException {
20 return din.readBoolean();
21 }
22 public final byte readByte() throws IOException {
23 return din.readByte();
24 }
25 public final char readChar() throws IOException {
26 din.readFully(work, 0, 2);
27 return (char) ((work[1] & 0xff) << 8 | (work[0] & 0xff));
28 }
29 public final double readDouble() throws IOException {
30 return Double.longBitsToDouble(readLong());
31 }
32 public final float readFloat() throws IOException {
33 return Float.intBitsToFloat(readInt());
34 }
35 public final void readFully(byte ba[]) throws IOException {
36 din.readFully(ba, 0, ba.length);
37 }
38 public final void readFully(byte ba[], int off, int len) throws IOException {
39 din.readFully(ba, off, len);
40 }
41 public final int readInt() throws IOException {
42 din.readFully(work, 0, 4);
43 return (work[3]) << 24 | (work[2] & 0xff) << 16 | (work[1] & 0xff) << 8 | (work[0] & 0xff);
44 }
45 public final String readLine() throws IOException {
46 return din.readLine();
47 }
48 public final long readLong() throws IOException {
49 din.readFully(work, 0, 8);
50 return (long) (work[7]) << 56 |
51