Java读取器和写入器(Reader/Writer)是基于字符的流。当要从数据源读取基于字符的数据时,使用读取器(Reader)。当想要写入基于字符的数据时使用写入器(Writer)。
如果有一个流提供字节,想通过将这些字节解码为字符读取字符,应该使用InputStreamReader类。
例如,如果有一个名为iso的InputStream对象,并且想要获取一个Reader对象实例,那么可以这样做:
Reader reader = new InputStreamReader(iso);
如果知道在基于字节的流中使用的编码,可在创建Reader对象时指定它,如下所示:
Reader reader = new InputStreamReader(iso, "US-ASCII");
类似地,可以创建一个Writer对象,从基于字节的输出流中输出的字符,如下所示,假设oso是一个OutputStream对象。以下代码使从OutputStream使用平台默认编码创建Writer对象。
Writer writer = new OutputStreamWriter(oso);
使用“US-ASCII”编码从OutputStream创建Writer对象
Writer writer = new OutputStreamWriter(oso, "US-ASCII");
示例 –
import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; public class Main { public static void main(String[] args) { String destFile = "test.txt"; try (BufferedWriter bw = new BufferedWriter(new FileWriter(destFile))) { bw.append("test"); bw.newLine(); bw.append("test1"); bw.newLine(); bw.append("test2"); bw.newLine(); bw.append("test3"); bw.flush(); } catch (Exception e2) { e2.printStackTrace(); } } }
以下代码从test.txt文件中读取文本。
import java.io.BufferedReader; import java.io.FileReader; public class Main { public static void main(String[] args) throws Exception{ String srcFile = "test.txt"; BufferedReader br = new BufferedReader(new FileReader(srcFile)); String text = null; while ((text = br.readLine()) != null) { System.out.println(text); } br.close(); } }
将基于字节的流转换为基于字符的流是直接的。如果有一个InputStream对象,可以通过将它包装在一个InputStreamReader对象中来获得一个Reader对象,如下所示:
InputStream is = create your InputStream object here; Reader reader = new InputStreamReader(is);
要从InputStream对象构造BufferedReader对象,那么可以这样做:
InputStream is = create your InputStream object here; BufferedReader br = new BufferedReader(new InputStreamReader(is));
可以从OutputStream对象构造一个Writer对象,如下所示:
OutputStream os = create your OutputStream object here; Writer writer = new OutputStreamWriter(os);
示例
import java.io.FileReader; import java.io.BufferedReader; import java.io.Reader; import java.io.FilterReader; import java.io.IOException; class LowerCaseReader extends FilterReader { public LowerCaseReader(Reader in) { super(in); } @Override public int read(char[] cbuf, int off, int len) throws IOException { int count = super.read(cbuf, off, len); if (count != -1) { // Convert all read characters to lowercase int limit = off + count; for (int i = off; i < limit; i++) { cbuf[i] = Character.toLowerCase(cbuf[i]); } } return count; } } public class Main { public static void main(String[] args) throws Exception { String fileName = "test.txt"; LowerCaseReader lcr = new LowerCaseReader(new FileReader(fileName)); int c = -1; while ((c = lcr.read()) != -1) { System.out.print((char) c); } lcr.close(); BufferedReader br = new BufferedReader(new LowerCaseReader(new FileReader(fileName))); String str = null; while ((str = br.readLine()) != null) { System.out.println(str); } br.close(); } }
执行上面代码,得到以下结果 –
Yiibai.com BufferedInputStream Usge. The Line 2..yiibai.com bufferedinputstream usge. the line 2..
¥ 我要打赏 纠错/补充 收藏