子类分别为FileReader与FileWriter
当默认使用GBK编码,可以采用子类读写
InputStreamReader示例:
public class InputStreamReaderDemo {
public static void main(String[] argStrings) {
// 转换流
// Reader的子类 为字符输入流
/*
* 解析字节
* 构造
* InputStreamReader(InputStream in)
* InputStreamReader(InputStream in, String charsetName)
*/
func();
}
public static void func() {
// TODO Auto-generated method stub
String file="e:\\utf.txt";
FileInputStream fileInputStream=null;
InputStreamReader inputStreamReader=null;
try {
// 创建字节输出流,绑定文件
fileInputStream=new FileInputStream(file);
// 转换流 默认编码GBK
inputStreamReader=new InputStreamReader(fileInputStream,"UTF-8");
// 转换流读数据
char[] cbuf=new char[1024];
int len=0;
while ((len=inputStreamReader.read(cbuf))!=-1) {
/*
* BOM的UTF-8编码文件时,从jdk1.4开始就会在读取的时候出现这个?了。
* 而且官方明确表示won't fix,所以现在用jdk6的时候仍然存在。
*解决办法其实就是改变文件的编码,改成无BOM的UTF-8就OK了。
*/
System.out.println(new String(cbuf,0,len));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (inputStreamReader!=null) {
inputStreamReader.close();
}
if (fileInputStream!=null) {
fileInputStream.close();
}
} catch (Exception e2) {
// TODO: handle exception
}
}
}
}
OutputStreamWriter示例:
public class OutputStreamWriterDemo {
public static void main(String[] argStrings) {
// 转换流
// Writer的子类 为字符输出流
/*
* 构造
* OutputStreamWriter(OutputStream out)
* OutputStreamWriter(OutputStream out, String charsetName)
*/
func();
}
public static void func() {
// TODO Auto-generated method stub
String file="e:\\fileOut.txt";
FileOutputStream fileOutputStream=null;
OutputStreamWriter outputStreamWriter=null;
try {
// 创建字节输出流,绑定文件
fileOutputStream=new FileOutputStream(file);
// 转换流 默认编码GBK
outputStreamWriter=new OutputStreamWriter(fileOutputStream,"UTF-8");
// 转换流写数据
outputStreamWriter.write("hello");
// Writer的子类 为字符输出流,每次操作write必须flush
outputStreamWriter.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (outputStreamWriter!=null) {
outputStreamWriter.close();
}
if (fileOutputStream!=null) {
fileOutputStream.close();
}
} catch (Exception e2) {
// TODO: handle exception
}
}
}
}
FileReader与FileWriter示例:
public class RWExam {
public static void main(String[] argStrings) {
// 字符流只能处理文本
func();
}
public static void func() {
// 1.输入流 输出流创建
String file="e:\\fileOut.txt";
FileReader fileReader=null;
FileWriter fileWriter=null;
try {
// 2.数据源 数据目的 绑定
fileReader=new FileReader(file);
fileWriter=new FileWriter("e:\\fileOut3.txt");
// 3.输入输出操作
char[] cbuf=new char[1024];
int len=0;
while ((len=fileReader.read(cbuf))!=-1) {
fileWriter.write(cbuf,0,len);
fileWriter.flush();
}
} catch (IOException e) {
// TODO: handle exception
throw new RuntimeException("文件复制失败");
} finally {
try {
if (fileReader!=null)
fileReader.close();
if (fileWriter!=null)
fileWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
throw new RuntimeException("释放资源失败");
}
}
}
}