Java InputStreamReader和OutputStreamWriter类的用法(附带实例)
InputStreamReader 类和 OutputStreamWriter 类是 Java 字节流通向字符流的桥梁。可以根据指定的编码方式,将字节流转换为字符流。
InputStreamReader 类的构造方法如下:
方法 ② 是将字节流 in 转换为字符流对象,charsetName 指定字符流的字符集,字符集主要有 US-ASCII、ISO-8859-1、UTF-8 和 UTF-16。如果指定的字符集不支持,就抛出 UnsupportedEncodingException 异常。
OutputStreamWriter 类的构造方法如下:
方法 ② 是将字节流 out 转换为字符流对象,charsetName 用于指定字符流的字符集。如果指定的字符集不支持,就会抛出 UnsupportedEncodingException 异常。
【实例】创建两个 File 类的对象,从其中一个文件中读取数据,并复制到另一个文件中,最终两个文件的内容相同。
InputStreamReader 类的构造方法如下:
① InputStreamReader(InputStream in)。 ② InputStreamReader(InputStream in,String charsetName)方法 ① 是将字节流 in 转换为字符流对象,字符流使用默认字符集。
方法 ② 是将字节流 in 转换为字符流对象,charsetName 指定字符流的字符集,字符集主要有 US-ASCII、ISO-8859-1、UTF-8 和 UTF-16。如果指定的字符集不支持,就抛出 UnsupportedEncodingException 异常。
OutputStreamWriter 类的构造方法如下:
① OutputStreamWriter(OutputStream out) ② OutputStreamWriter(OutputStream out,String charsetName)方法 ① 是将字节流 out 转换为字符流对象,字符流使用默认字符集。
方法 ② 是将字节流 out 转换为字符流对象,charsetName 用于指定字符流的字符集。如果指定的字符集不支持,就会抛出 UnsupportedEncodingException 异常。
【实例】创建两个 File 类的对象,从其中一个文件中读取数据,并复制到另一个文件中,最终两个文件的内容相同。
import java.io.*; public class Example { public static void main(String[] args) { File filein = new File( "D:\\Example.java"); File fileout = new File("D:\\chapter\\back_Example.java"); FileInputStream fis; try { // 如果文件不存在 if (!filein.exists()) // 创建新文件 filein.createNewFile(); // 如果文件不存在 if (!fileout.exists()) // 创建新文件 fileout.createNewFile(); fis = new FileInputStream(filein); FileOutputStream fos = new FileOutputStream(fileout); InputStreamReader in = new InputStreamReader(fis); OutputStreamWriter out = new OutputStreamWriter(fos); int is; while ((is = in.read()) != -1) { out.write(is); } in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } }运行程序后,会将位于 D:\Example.java 的文件内容复制到 D:\chapter\back_Example.java 文件中。