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();
}
}
執行上面程式碼,得到以下結果 -
Tw511.com BufferedInputStream Usge.
The Line 2..tw511.com bufferedinputstream usge.
the line 2..