如何将字符串写入OutputStream [英] How to write Strings to an OutputStream

查看:496
本文介绍了如何将字符串写入OutputStream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建实现 OutputStream 的类并将内容写入其中?

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 will not compile. What are the options or better techniques?

public class FooBarPrinter{
    private OutputStream o;
    public FooBarPrinter(OutputStream o){
        this.o=o;
    }

    public void print(String s){        
        o.write(s);
    }
}


推荐答案

A泛型 OutputStream 无法直接向其写入 String 。相反,您需要获取 String byte [] ,然后将它们写入流中。

A generic OutputStream doesn't have the ability to write a String directly to it. Instead, you need to get the byte[] of the String and then write them out to the stream.

public void print(String s){ 
    o.write(s.getBytes());
}

请参阅 OutputStream java文档,了解有关支持的写入数据类型的更多信息。

Refer to the OutputStream java documentation for more information on the supported write data types.

我建议更好的建议是确保你在构造函数中提供的 OutputStream BufferedOutputStream ,因为这会提高代码的性能。它的工作原理是缓冲内存中的一些数据,并以大块的形式将其写入磁盘而不是许多较小的写入。

My suggestion for making this better is to make sure the OutputStream you provide in the constructor is a BufferedOutputStream, as this will improve the performance of your code. It works by buffering some of the data in memory, and writing it out to disk in big chunks instead of many smaller writes.

这是 BufferedOutputStream

这篇关于如何将字符串写入OutputStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆