Java如何将InputStream转换为Reader

InputStreamReader类可以将InputStream转换为Reader。 它读取字节并将其解码为字符。

下面是一个InputStreamReader类的示例。文件:InputStreamReaderExample.java

package com.yiibai.tutorial.io;  import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader;  /**  * @author yiibai  */ public class InputStreamReaderExample {     public static void main(String[] args) {         String input = "This is an example of InputStreamReader";         InputStream inputStream = null;         Reader reader = null;         try {             inputStream = new ByteArrayInputStream(input.getBytes());             // Conversion of InputStream to Reader             reader = new InputStreamReader(inputStream, "UTF-8");              int i;             while ((i = reader.read()) != -1) {                 System.out.print((char) i);             }         } catch (IOException e) {             e.printStackTrace();         } finally {             try {                 if (reader != null) {                     reader.close();                 }             } catch (IOException e) {                 e.printStackTrace();             }         }     } } 

执行上面示例代码,得到以下结果:

This is an example of InputStreamReader 

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/264100.html

(0)
上一篇 2022年6月7日 00:06
下一篇 2022年6月7日 00:06

相关推荐

发表回复

登录后才能评论