`
kong6001
  • 浏览: 142167 次
  • 性别: Icon_minigender_1
  • 来自: 广东广州
社区版块
存档分类
最新评论

Convert a Java Writer to a Reader

    博客分类:
  • IO
阅读更多

原文地址:ostermiller.org/convert_java_writer_reader.html

Convert a Java Writer to a Reader

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

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

Method 1: Buffer the data using a String

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

  StringWriter out = new StringWriter();
  class1.putDataOnWriter(out);
  class2.processDataFromReader(
    new StringReader(out.toString())
  );

That's it! The Writer has been converted to a Reader.

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 PipedWriter. The current thread can then read the data as it comes in.

  PipedReader in = new PipedReader();
  PipedWriter out = new PipedWriter(in);
  new Thread(
    new Runnable(){
      public void run(){
        class1.putDataOnWriter(out);
      }
    }
  ).start();
  class2.processDataFromReader(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 "two 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

  CircularCharBuffer ccb = new CircularCharBuffer();
  new Thread(
    new Runnable(){
      public void run(){
        class1.putDataOnWriter(ccb.getWriter());
      }
    }
  ).start();
  class2.processDataFromReader(ccb.getReader());

Single Threaded Example of a Circular Buffer

  // buffer all data in a circular buffer of infinite size
  CircularCharBuffer ccb = new CircularCharBuffer(CircularCharBuffer.INFINITE_SIZE);
  class1.putDataOnWriter(ccb.getWriter());
  class2.processDataFromReader(ccb.getReader());

See also: Converting an OutputStream to an InputStream

分享到:
评论

相关推荐

    一些与java相关的东西

    字符流主要处理Unicode字符,如Reader和Writer类,而字节流处理原始的8位字节数据,如InputStream和OutputStream类。还有缓冲流(Buffered streams)可以提高效率,转换流(Convert streams)用于在不同类型的流之间...

    java io 系列操作代码练习 Java学习资料

    字符流处理Unicode字符,如Reader和Writer。缓冲流提高读写效率,转换流用于字节流和字符流之间的转换,对象流用于序列化和反序列化对象。 二、基本IO类 1. FileInputStream和FileOutputStream:分别用于读取和写入...

    Java中文问题详解(高手必读)

    在Java中,`InputStream`和`OutputStream`用于处理字节流,而`Reader`和`Writer`则专门用于处理字符流。在读取或写入文本文件时,应优先考虑使用`Reader`和`Writer`,因为它们可以自动处理字符编码问题。 ```java /...

    Java中文问题详解

    在Java中,`Reader`和`Writer`类用于处理字符流,而`InputStream`和`OutputStream`类用于处理字节流。当我们需要读取或写入文本文件时,通常会选择使用`Reader`和`Writer`,因为它们能够直接处理字符,避免了编码...

    javajsp中 中文问题详解

    在Java中,`Reader`和`Writer`类用于处理字符流,而`InputStream`和`OutputStream`类用于处理字节流。例如,读取一个文本文件中的中文字符,应使用`InputStreamReader`,并指定正确的编码: ```java ...

    Google C++ Style Guide(Google C++编程规范)高清PDF

    Note that this guide is not a C++ tutorial: we assume that the reader is familiar with the language. Header Files In general, every .cc file should have an associated .h file. There are some common ...

    使用XStream是实现XML与Java对象的转换(4)--转换器

    在Java开发中,数据序列化和反序列化是一项常见的任务,它允许我们将对象的状态转换为持久化的形式(如XML或JSON),以便存储或传输。XStream是一个强大的库,专门用于XML与Java对象之间的转换。本篇文章将深入探讨...

    HTML to PDF

    HtmlConverter.convertToPdf(reader, document); } catch (IOException e) { e.printStackTrace(); } finally { document.close(); } } } ``` 在这个例子中,我们首先使用jsoup解析HTML字符串,然后创建`...

    转载 xStream完美转换XML、JSON

    标题 "xStream完美转换XML、JSON" 指的是使用xStream库在Java中进行XML与JSON数据格式之间的转换。xStream是一个强大的库,它提供了一种简单的方式来序列化和反序列化Java对象到XML,反之亦然。在这个场景中,它同样...

    XStream的Date转换 @XStreamConverter DateConverter

    在Java开发中,数据序列化和反序列化是常见的需求,XStream库提供了一个方便的解决方案。XStream是一个用于XML、JSON和HTML的Java库,它能够将Java对象转化为XML,反之也能将XML数据还原为Java对象。在这个场景中,...

    hibernate 自动导入 sql 文件 import.sql 国际化编码的问题的解决方案

    sce.getServletContext().log("Convert " + fileName + " to import.sql"); String srcEnc = fileName.substring(fileName.lastIndexOf(".") + 1); try { Reader reader = new InputStreamReader(HibListener....

    xStream转换xml和json源码

    xStream是一个轻量级的Java库,用于将Java对象序列化为XML,同时也能将XML反序列化回Java对象。这个强大的工具同样支持JSON格式,使得在Java应用程序中处理XML和JSON数据变得非常便捷。本篇文章将深入探讨xStream...

    JsonRW:读取和写入 .json 的简单 java 程序

    // Convert back to Java object ``` JsonRW-master 压缩包很可能包含了该项目的源代码,包括类文件、测试用例等。要深入了解 JsonRW 的实现细节,可以解压文件并查看源代码,例如 `JsonRW.java` 或其他相关的 `....

    图书管理系统IO流版.zip

    字符流则用于处理文本数据,如XML、JSON格式的图书信息,常用类有Reader和Writer。 - Java还提供了缓冲流(Buffered Stream)、转换流(Convert Stream)以及对象流(Object Stream),用于提高效率、实现不同类型...

    使用XStream操作xml教程

    首先创建一个Java对象,然后使用XStream实例的`toXML()`方法将其转换为XML字符串。 ```java import com.thoughtworks.xstream.XStream; public class User { private String name; private int age; // 构造器...

    XStream简单应用实例

    String xml = xstream.toXML(person); System.out.println(xml); // 反序列化回Java对象 Person deserializedPerson = (Person) xstream.fromXML(xml); System.out.println(deserializedPerson); } } class ...

    class_classjavaj_

    这些类分别将InputStream和OutputStream与字符流(如Reader和Writer)连接起来,使得处理文本数据变得方便。 5. **对象流(Object Streams)**: 对于序列化和反序列化Java对象,Java提供了ObjectInputStream和...

    ffmpeg.exe

    reader.addListener(writer); while (reader.readPacket() == null) ; writer.close(); outputFile.close(); System.out.println("转换成功"); } } ``` 以上代码展示了如何在Java中调用`ffmpeg.exe`进行视频...

    Jaxb2实现JavaBean与xml互转的方法详解

    public static String convertToXml(Object obj, String encoding) { JAXBContext context = JAXBContext.newInstance(obj.getClass()); Marshaller marshaller = context.createMarshaller(); marshaller.set...

    python3.6.5参考手册 chm

    PEP 523: Adding a frame evaluation API to CPython PYTHONMALLOC environment variable DTrace and SystemTap probing support Other Language Changes New Modules secrets Improved Modules array ast ...

Global site tag (gtag.js) - Google Analytics