字符流的处理和字节流差不多,API基本上完全一样,就是计量单位不同。另外字符流还提供一些其他的处理流,比如按行读取流、字符串流等等。
特别注意,当文件有汉字时,注意编码格式:
//设置流的编码格式,防止乱码
InputStreamReader isr = new InputStreamReader(
new FileInputStream("f:/poem.txt"), "gbk");
BufferedReader fReader = new BufferedReader( isr );
InputStreamReader isr = new InputStreamReader(
new FileInputStream("f:/poem.txt"), "gbk");
BufferedReader fReader = new BufferedReader( isr );
下面给个例子看看:
import
java.io.*;
/**
* 字符流测试
*
* @author leizhimin 2008-8-27 22:16:44
*/
public class TestIOStream {
public static void main(String[] args) {
testReaderWriter();
testLineNumberReader();
}
/**
* 带缓冲的字符流
*/
public static void testReaderWriter() {
int bufsize = 25;
try {
BufferedReader bufferedReader = new BufferedReader( new FileReader( new File( "C:\\x.txt")));
BufferedWriter bufferedWriter = new BufferedWriter( new FileWriter( new File( "C:\\xb.txt")));
char buf[] = new char[bufsize]; //字符缓冲区
while (bufferedReader.read(buf) != -1) {
bufferedWriter.write(buf);
}
bufferedWriter.flush();
bufferedReader.close();
bufferedWriter.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 按行读取的字符流
*/
public static void testLineNumberReader() {
try {
LineNumberReader lineNumberReader = new LineNumberReader( new BufferedReader( new FileReader( new File( "C:\\x.txt"))));
String lineString; //行字符串变量
int x = 0; //行号
while ((lineString = lineNumberReader.readLine()) != null) {
x++;
System.out.println( "行号:" + x + " >>>" + lineString);
}
lineNumberReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 字符流测试
*
* @author leizhimin 2008-8-27 22:16:44
*/
public class TestIOStream {
public static void main(String[] args) {
testReaderWriter();
testLineNumberReader();
}
/**
* 带缓冲的字符流
*/
public static void testReaderWriter() {
int bufsize = 25;
try {
BufferedReader bufferedReader = new BufferedReader( new FileReader( new File( "C:\\x.txt")));
BufferedWriter bufferedWriter = new BufferedWriter( new FileWriter( new File( "C:\\xb.txt")));
char buf[] = new char[bufsize]; //字符缓冲区
while (bufferedReader.read(buf) != -1) {
bufferedWriter.write(buf);
}
bufferedWriter.flush();
bufferedReader.close();
bufferedWriter.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 按行读取的字符流
*/
public static void testLineNumberReader() {
try {
LineNumberReader lineNumberReader = new LineNumberReader( new BufferedReader( new FileReader( new File( "C:\\x.txt"))));
String lineString; //行字符串变量
int x = 0; //行号
while ((lineString = lineNumberReader.readLine()) != null) {
x++;
System.out.println( "行号:" + x + " >>>" + lineString);
}
lineNumberReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行结果:
行号:1 >>>白日依山尽,黄河入海流。
行号:2 >>>欲穷千里目,更上一层楼。
行号:3 >>>
行号:4 >>>—— 王之涣《登鹳雀楼》
行号:2 >>>欲穷千里目,更上一层楼。
行号:3 >>>
行号:4 >>>—— 王之涣《登鹳雀楼》