我试图对你的法典作必要的最低限度修改,使之发挥作用。 斜体是提供双向版本流拷贝的良好工作。
public class Test {
private static final String FORMAT = "UTF-8";
private static final int BUFFER_SIZE = 10; // for demonstration purposes.
public static void main(String[] args) throws Exception {
String string = "This is a test of the public broadcast system";
int clen = string.length();
ByteArrayInputStream in = new ByteArrayInputStream(string.getBytes(FORMAT));
OutputStream out = System.out;
int pos = 0, total_pos = 0;
byte[] buffer = new byte[BUFFER_SIZE];
while (pos != -1) {
pos = in.read(buffer, 0, BUFFER_SIZE);
if (pos > 0) {
total_pos += pos;
out.write(buffer, 0, pos);
setProgress((int) (total_pos * 100 / clen));
}
}
}
private static void setProgress(int i) {
}
}
- You were ignoring the value of pos when you were writing out the buffer to the output stream.
- You also need to re-check the value of pos because it may have just read the end of the file. You don t increment the total_pos in that case (although you should probably report that you are 100% complete)
- Be sure to handle your resources correctly with close()s in the appropriate places.
-edit-
The general reason for using an array as a buffer is so that the output stream can do as much work as it can with a larger set of data.
写给青少年可能不会造成很多延误,但可能是一个网络的袖珍,正被写给或一些其他缓慢装置。 As the JavaDoc states
产出Stream的书写方法要求书面说明每一 by子的一条理由。 鼓励下级单位超越这一方法,提供更有效的执行。
在使用布置式投入/投放机时使用该软件的好处可能很小。