天天看點

java的無緩沖輸出_java io系列24之 BufferedWriter(字元緩沖輸出流)

}

73

74 // 将字元數組cbuf寫入到緩沖中,從cbuf的off位置開始寫入,寫入長度是len。

75 public void write(char cbuf[], int off, int len) throws IOException {

76 synchronized (lock) {

77 ensureOpen();

78 if ((off < 0) || (off > cbuf.length) || (len < 0) ||

79 ((off + len) > cbuf.length) || ((off + len) < 0)) {

80 throw new IndexOutOfBoundsException();

81 } else if (len == 0) {

82 return;

83 }

84

85 if (len >= nChars) {

86

89 flushBuffer();

90 out.write(cbuf, off, len);

91 return;

92 }

93

94 int b = off, t = off + len;

95 while (b < t) {

96 int d = min(nChars - nextChar, t - b);

97 System.arraycopy(cbuf, b, cb, nextChar, d);

98 b += d;

99 nextChar += d;

100 if (nextChar >= nChars)

101 flushBuffer();

102 }

103 }

104 }

105

106 // 将字元串s寫入到緩沖中,從s的off位置開始寫入,寫入長度是len。

107 public void write(String s, int off, int len) throws IOException {

108 synchronized (lock) {

109 ensureOpen();

110

111 int b = off, t = off + len;

112 while (b < t) {

113 int d = min(nChars - nextChar, t - b);

114 s.getChars(b, b + d, cb, nextChar);

115 b += d;

116 nextChar += d;

117 if (nextChar >= nChars)

118 flushBuffer();

119 }

120 }

121 }

122

123 // 将換行符寫入到緩沖中

124 public void newLine() throws IOException {

125 write(lineSeparator);

126 }

127

128 // 清空緩沖區資料

129 public void flush() throws IOException {

130 synchronized (lock) {

131 flushBuffer();

132 out.flush();

133 }

134 }

135

136 public void close() throws IOException {

137 synchronized (lock) {

138 if (out == null) {

139 return;

140 }

141 try {

142 flushBuffer();

143 } finally {

144 out.close();

145 out = null;

146 cb = null;

147 }

148 }

149 }

150 }