`

将String转换成InputStream

    博客分类:
  • j2se
阅读更多

简单如下:
String   str   =   "";//add   your   string   content
//设置xmltag.getBytes("UTF-8") 编码
InputStream   inputStream   =   new   ByteArrayInputStream(str.getBytes());

 

 

Convert a Java OutputStream to an InputStream

 

 

If you have ever programmed using Java IO, you will quickly run into a situation in which a class creates data on an OutputStream and you need to send it to another class that expects to read the data from an input stream. You'll soon be asking the question, "How do I convert an OutputStream to an InputStream?"

Nowhere in Java will you find a OutpStreamToInputStreamConverter class. Luckily, there are several ways to go about this.

Method 1: Buffer the data using a byte array

The easiest method is to buffer the data using a byte array. The code will look something like this:

  ByteArrayOutputStream out = new ByteArrayOutputStream();
  class1.putDataOnOutputStream(out);
  class2.processDataFromInputStream(
    new ByteArrayInputStream(out.toByteArray())
  );

That's it! The OutputStream has been converted to an InputStream.

Method 2: Use pipes

The problem with the first method is that you must actually have enough memory to buffer the entire amount of data. You could buffer larger amounts of data by using the filesystem rather than memory, but either way there is a hard limit to the size of the data that can be handled. The solution is create a thread to produce the data to the PipedOutputStream. The current thread can then read the data as it comes in.

  PipedInputStream in = new PipedInputStream();
  PipedOUtputStream out = new PipedOutputStream(in);
  new Thread(
    new Runnable(){
      public void run(){
        class1.putDataOnOutputStream(out);
      }
    }
  ).start();
  class2.processDataFromInputStream(in);

Method 3: Use Circular Buffers

The two piped streams in method two actually manage a hidden circular buffer. It is conceptually easier to use an explicit Circular Buffer. CircularBuffers offer several advantages:

  • One CircularBuffer class rather than two pipe classes.
  • It is easier to convert between the "buffer all data" and "extra threads" approaches.
  • You can change the buffer size rather than relying on the hard-coded 1k of buffer in the pipes.

Multiple Threaded Example of a Circular Buffer

  CircularByteBuffer cbb = new CircularByteBuffer();
  new Thread(
    new Runnable(){
      public void run(){
        class1.putDataOnOutputStream(cbb.getOutputStream());
      }
    }
  ).start();
  class2.processDataFromInputStream(cbb.getInputStream());

Single Threaded Example of a Circular Buffer

  // buffer all data in a circular buffer of infinite size
  CircularByteBuffer cbb = new CircularByteBuffer(CircularByteBuffer.INFINITE_SIZE);
  class1.putDataOnOutputStream(cbb.getOutputStream());
  class2.processDataFromInputStream(cbb.getInputStream());

See also: Converting a Writer to a Reader

ostermiller.org (site index)

Copyright Stephen Ostermiller 1996-2008

分享到:
评论
1 楼 LetCode 2011-11-01  
 

相关推荐

    XmlToJson:Android库,用于将XML转换为JSON以及将JSON转换为XML

    XML to JSON是一个Android Studio库,可轻松将XML转换为JSON以及将JSON转换为XML 。 它是完全可配置的,因此您可以更改例如属性名称。 与gradle集成很容易。 XML到JSON 基本用法 有两种创建XmlToJson对象的方法:...

    java 中InputStream,String,File之间的相互转化对比

    主要介绍了java 中InputStream,String,File之间的相互转化对比的相关资料,需要的朋友可以参考下

    java excel导入导出工具

    一个在 Java 对象和 Excel 文档之间进行转换的迅速而灵活的工具 1、Excel导出:支持Java对象装换为Excel,...2、Excel导入:支持Excel转换为Java对象,并且支持File、InputStream、文件路径、Workbook等多种导入方式;

    Java 获取URL的内容

    第一:创建HttpURLConnection 第二:打开URL,创建一个InputStream 第三:逐行(逐字节)读取,如果需要,转换编码,放入字符串。 好,一下就开始代码吧: 代码如下:public String getUrlContent(String path){ ...

    day019-io笔记和代码.rar

    * 3.String(byte[] bytes) 根据默认字符集将字节数组转换为字符串 * 4.String(byte[] bytes, String charsetName) * 根据默认字符集将字节数组转换为字符串 * * 这里会有乱码问题: ...

    mutator-io:一个小库来处理(大)数据转换

    Mutator I / O中“管道”的概念只是将递到 interface Pipe { name : string in : InputStream out : OutputStream } import { MutatorIO } from 'mutator-io' import * as MqttInputStream from 'mutator-io-...

    Java文件处理工具类--FileUtil

    public static String readFileAsString(InputStream in) throws Exception { String content = new String(readFileBinary(in)); return content; } /** * Read content from local file to binary byte...

    Excel POI读取封装(文件+示范代码)

    // 将从Excel表格读取到的数据与配置文件筛选成可以插入到数据库的数据 public List<HashMap<String, Object>> parseExcelData( List<HashMap<String, String>> excelDataMap, Map<String, List<ExcelMap>> ...

    office在线查看

    该转换工具用来将pdf文件转换成swf文件。改工具既可以安装使用实现文件转换,也拷贝安装后Program Files下的Swftools文件夹放到工程中,以绿色软件方式来使用。转换命令将在FileConverterUtil.java中特别指明。 第四...

    jsp内置对象的用法

    6 String toString() 把此Object对象转换成String类的对象 7 void notify() 唤醒一个等待的线程 8 void notifyAll() 唤醒所有等待的线程 9 void wait(int timeout) 使一个线程处于等待直到timeout结束或被...

    java7源码-java-convert-example:本项目记录一些常见对象转换的方法,例如:文件转换、日期时间转换、stream流转换、

    平时的java项目中会存在各种对象的互相转换的情况,本项目记录一些常见对象转换的方法,例如:文件转换、日期时间转换、stream流转换、集合对象转换等 文件 Java 为文件操作设计了很多的类,有数据相关的 IO Stream ...

    简单的JavaExcel进程sep4j.zip

    sep4J: Simple Excel Processing for Java , 通过一次静态方法调用完成 excel <-> List之间的转换。 你不必手写任何 POI 相关代码。支持 Maven. 基本示例把数据写入Excel Collection users = Arrays.asList...

    ffmpeg-20170620-ae6f6d4-win64

    public OutHandler(InputStream is, String type) { br = new BufferedReader(new InputStreamReader(is)); this.type = type; } /** * 重写线程销毁方法,安全的关闭线程 */ @...

    Android开发人员不得不收集的代码

    inputStream2String, string2InputStream : inputStream 与 string 按编码互转 outputStream2String, string2OutputStream: outputStream 与 string 按编码互转 bitmap2Bytes, bytes2Bitmap : bitmap 与 byteArr 互...

    Java之IO流学习总结

    CharReader、StringReader 是两种基本的介质流,它们分别将Char 数组、String中读取数据。PipedReader 是从与其它线程共用的管道中读取数据。 BufferedReader 很明显就是一个装饰器,它和其子类负责装饰其它Reader ...

    android xml文件操作

    * 将一个xml字符串解析成Document对象。 * * @param xmlStr * 要被解析的xml字符串。 * @param encoding * 字符串的编码。 * @return 返回解析后的Document对象。 * @throws IOException * 如果...

    JsonParserGenerator:(已放弃)我们有一个更好的方法来生成 JSON、protobuf、SQLite 数据库模式。 但我们没有时间开源

    则需要在构造函数之外链接递归数据更有力你可以编写转换器代码来在类型之间进行转换,所以基本上你可以拥有所有的东西,所以基本上你可以在解析时注入任何你想要的代码: lazy val ApiTimeStringToDate = ...

    jbpm流程控制初学者容易接触的domo

    //要把流程图转换成java对象 InputStream is=new FileInputStream("D://java_dianli//jbpm//src//leave//leave.zip"); ZipInputStream zis=new ZipInputStream(is); ProcessDefinition pd=ProcessDefinition....

    byte-streams:用于jvm字节表示的Rosetta Stone

    记住如何在它们之间进行转换是一项不费力的任务,而通过定义它们自己的自定义表示形式的库,或者将它们与Clojure的惰性序列和流表示形式组合在一起,使情况变得更糟。 该库是Java提供的所有字节表示形式的Rosetta...

    计算机网络实验报告 获取MAC socket通信

    // 转换成网络输出流 java.net.ServerSocket ss = new java.net.ServerSocket(9000); java.net.Socket sk = ss.accept(); //DataOutputStream 处理数据 数据的输出流 java.io.OutputStream os = new java.io...

Global site tag (gtag.js) - Google Analytics