Java InputStreamReader and OutputStreamWriter
InputStreamReader
InputStreamReader is a bridge of byte flow to character streams: it reads bytes using the specified charset and decodes them into characters. The character set it uses can be specified by name or explicitly given, or the platform default character set can be accepted.
Construction method
Construction Method |
Description |
InputStreamReader (InputStream in) |
Create a inputstreamreader that uses the default character set |
InputStreamReader (InputStream in, String CharsetName) |
Create a inputstreamreader using the specified character set |
Method
Method |
Description |
GetEncoding () |
Returns the name of the character encoding used by this stream |
Read () |
Read a single character |
Read (char[] cbuf, int offset, int length) |
To read a character into a part of an array |
Close () |
Closes the stream and releases all resources associated with it |
OutputStreamWriter
OutputStreamWriter is a bridge of character flow to byte streams: You can encode bytes into characters that you specify charset to write to the stream. The character set it uses can be specified by name or explicitly given, otherwise the platform default character set will be accepted.
Construction method
Construction Method |
Description |
OutputStreamWriter (OutputStream out) |
Create a outputstreamwriter that uses the default character encoding |
OutputStreamWriter (OutputStream out, String charsetname) |
Create a outputstreamwriter using the specified character set |
Method
Method |
Description |
GetEncoding () |
Returns the name of the character encoding used by this stream |
Write (int c) |
Write a single character |
Write (char[] cbuf, int off, int len) |
Writes to a part of a character array |
Write (String str, int off, int len) |
Write to a part of a string |
Close () |
Close this stream, but first refresh it |
Copy File Example
inputstreamreader input = null;
OutputStreamWriter output = null;
try {//create the input output stream and make the character encoding set input = new InputStreamReader (New FileInputStream ("E:/readme.txt"), "Utf-8");
Output = new OutputStreamWriter (New FileOutputStream ("D:/temp.txt"), "Utf-8");
char[] buffer = new char[1024 * 8];
int Len;
Read and write data while (len = input.read (buffer) > 0) {output.write (buffer, 0, Len);
//Be sure to refresh to ensure that all data in the buffer is written to the file Output.flush ();
System.out.println ("done.");
The catch (IOException e) {try {//Close input stream if (input!= null) {input.close ();
} catch (IOException E2) {e.printstacktrace ();
Finally {try {//Turn off output stream if (output!= null) {output.close ();
} catch (IOException E3) {e.printstacktrace (); }
}
}