先回答你第一个问题
read是一次读取一个字节的,而中文编码一个中文是2个字节(一个字符),所有是乱码
这就涉及到编码问题, 参数里能传入编码的流有InputStreamReader, 但是InputStreamReader 构造方法传入的另一个参数还必须是字节流,所有又必须用到字节流到字符流的转换问题.
我的代码,经过测试,完美通过
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
class BufferedReaderDemo
{
public static void main(String[] args) throws IOException
{
methed_2();
}
public static void methed_2() throws IOException
{
FileInputStream fr = new FileInputStream("OutputStreamDemo.txt");
InputStreamReader isr = new InputStreamReader(fr, "UTF-8");
BufferedReader bufr = new BufferedReader(isr);
String line = null;
while ((line = bufr.readLine()) != null)
{
System.out.print(line);
}
bufr.close();
}
}
因为InputStreamReader和BufferedReader 都继承自Reader,而BufferedReader 的构造器又是Reader.
Writer也是一样的处理
BufferedWriter oWriter = new BufferedWriter(new OutputStreamWriter(writerStream, "UTF-8"));
|