簡體   English   中英

擴展OutputStream類; write(int)方法

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM