How to write Strings to an OutputStream

后端 未结 3 1683
谎友^
谎友^ 2021-01-11 14:23

How can I create class that takes an implentation of OutputStream and writes the the content to it?

For example, the following print method is wrong and

3条回答
  •  感情败类
    2021-01-11 14:57

    To write out strings, take a look at the PrintStream class. You can see an example of a class that does what you intend here.

    Also, you can wrap an OutputStream using one of the PrintStream constructors:

    public class FooBarPrinter{
      private PrintStream p;
      public FooBarPrinter(OutputStream o){
        p = new PrintStream(o);
      }
      public void print(String s){      
        p.print(s);
      }
    }
    

    EDIT: note that you can also use the PrintWriter class in the same manner as PrintStream above; which is typically better because you can specify the encoding to use, avoiding any platform dependencies.

提交回复
热议问题