- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to convert an OutputStream to a Writer in Java?
An OutputStream class is a byte-oriented whereas Writer class is a character-oriented. We can convert an OutputStream class to a Writer class using an OutputStreamWriter class and pass an argument of ByteArrayOutputStream object to OutputStreamWriter constructor.
An OutputStreamWriter is a bridge from a character stream to a byte stream, the characters written to it are encoded into bytes using a specified charset.
Syntax
public class OutputStreamWriter extends Writer
Example
import java.io.*; public class OutputStreamToWriterTest { public static void main(String[] args) throws Exception { String str = "TUTORIALSPOINT"; ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(baos); for (int i=0; i < str.length(); i++) { osw.write((int) str.charAt(i)); } osw.close(); byte[] b = baos.toByteArray(); for (int j=0; j < b.length; j++) { System.out.println(b[j]); } } }
Output
84 85 84 79 82 73 65 76 83 80 79 73 78 84
Advertisements