简体   繁体   中英

Extending OutputStream class; write(int) method

So my goal is to implement the write method in the class OutputStream to create a new class NumStream, which basically converts ints to Strings. Here is my sample code:

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
    }
}

I've tried using several different approaches, and my result always results in the program compiling, but when I run it, nothing happens. So far I've tried using switch statements to produce this result:

public void write(int c) throws IOException {
StringBuffer sb = new StringBuffer();
    switch (c) {
        case 1: sb.append("1");
        break;
    //etc. through 9

I'm unsure of what to do or try next to produce a result. :/ Any tips to steer me in the right direction?

I had the same problem too, Here is the solution:

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);
 }
}

All we need to do is to implement the "write" method correctly which is clearly instructed in the above example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM