[英]Extending OutputStream class; write(int) method
因此,我的目标是在OutputStream类中实现write方法以创建一个新的NumStream类,该类基本上将int转换为Strings。 这是我的示例代码:
import java.io.*;
public class NumStream extends OutputStream {
public void write(int c) throws IOException {
// What goes here?
}
public static void main(String[] args) {
NumStream ns = new NumStream();
PrintWriter pw = new PrintWriter(new OutputStreamWriter(ns));
pw.println("123456789 and ! and # ");
pw.flush(); // needed for anything to happen, try taking it out
}
}
我尝试使用几种不同的方法,但结果总是会导致程序编译,但是运行它时,什么也没发生。 到目前为止,我已经尝试使用switch语句产生以下结果:
public void write(int c) throws IOException {
StringBuffer sb = new StringBuffer();
switch (c) {
case 1: sb.append("1");
break;
//etc. through 9
我不确定该怎么做或下一步尝试产生结果。 :/有什么技巧可以引导我朝正确的方向发展?
我也有同样的问题,这是解决方案:
public class MyOutputStream extends OutputStream {
StringBuilder anotatedText;
public MyOutputStream() {
// Custom constructor
}
@Override
public void write(int b) {
int[] bytes = {b};
write(bytes, 0, bytes.length);
}
public void write(int[] bytes, int offset, int length) {
String s = new String(bytes, offset, length);
anotatedText.append(s);
}
public void myPrint() {
System.out.println(anotatedText);
}
}
我们需要做的就是正确实现“写”方法,以上示例中已明确指示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.