[英]BufferedOutputStream not writing to standardIO
我正在尝试使用Robert Sedgwick在他的Algorithms 4E教科书中提供的BinaryStdOut.java类。 该课程的代码可在他的网站上免费获得,但是为了便于参考,我将在此处显示其相关的摘要。
在上面提到的类中,BufferedOutputStream声明如下
private static BufferedOutputStream out = new BufferedOutputStream(System.out);
如果我的理解是正确的,这应该允许out.write()
本质上按照标准输出,就像我要使用System.out.print()
。
为了对此进行测试,我构建了一个程序,其主要功能如下
public static void main(String[] args) {
BinaryStdOut.write(1);
}
这会将整数1传递给BinaryStdOut的write()
方法,如下所示
public static void write(int x) {
writeByte((x >>> 24) & 0xff);
writeByte((x >>> 16) & 0xff);
writeByte((x >>> 8) & 0xff);
writeByte((x >>> 0) & 0xff);
}
writeByte()
代码为:
private static void writeByte(int x) {
assert x >= 0 && x < 256;
// optimized if byte-aligned
if (N == 0) {
try { out.write(x); }
catch (IOException e) { e.printStackTrace(); }
return;
}
// otherwise write one bit at a time
for (int i = 0; i < 8; i++) {
boolean bit = ((x >>> (8 - i - 1)) & 1) == 1;
writeBit(bit);
}
}
现在我的问题是测试代码似乎没有执行任何操作。 它可以编译并成功运行,但是不会像在System.out.print()
使用相同的整数那样在终端中打印任何内容。
为了查看问题是否出在BinaryStdOut类上,我将BufferedOutputStream声明复制到我的主程序中,然后尝试直接写入该流,并得到相同的结果。
使用BufferedOutputStream.write()
是否缺少某些内容?
编辑:我的测试程序的主要功能当前如下所示:
public static void main(String[] args) {
// TODO Auto-generated method stub
BufferedOutputStream out = new BufferedOutputStream(System.out);
try {out.write(16);
out.flush();
out.close();}
catch(IOException e){
System.out.println("error");
}
}
写入缓冲区后,需要刷新缓冲区:
// optimized if byte-aligned
if (N == 0) {
try {
out.write(x);
out.flush();
}
catch (IOException e) { e.printStackTrace(); }
return;
}
您的测试程序似乎什么都不显示的原因是因为您正在打印DLE ,它是控制字符,不会在stdout中显示。
这为我打印了一个世界,您是否选择了一些没有可显示字形的字节? 而且您可能不应该这样关闭System.out
(在BuffedOutputStream上调用close将其关闭并释放与该流关联的所有系统资源)。
public static void main(String[] args) {
BufferedOutputStream out = new BufferedOutputStream(
System.out);
String msg = "Hello, World!";
try {
for (char c : msg.toCharArray()) {
out.write(c);
}
out.flush();
} catch (IOException e) {
System.out.println("error");
}
}
是的,您需要flush
,为什么需要flush
是因为使用了Buffered
流:
的BufferedOutputStream:
public BufferedOutputStream(OutputStream out) {
this(out, 8192);//default buffer size
}
public synchronized void write(int b) throws IOException {
if (count >= buf.length) {
flushBuffer();
}
buf[count++] = (byte)b;
}
因此,在缓冲区中充满8KB数据之前,内容将一直保持缓冲状态,而不会流入控制台。
在write(16)
您应该在控制台(至少是Eclipse IDE)上看到print char,如果您打印1601-1626,则应该看到A
- Z
字符已打印。 ?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.