本文实例为大家分享了文件字符流的使用方法,供大家参考,具体内容如下
案例1:
读取一个文件并写入到另一个文件中,char[] 来中转。
首先要在E盘下创建一个文本文档,命名为test.txt,输入一些字符串。
public class Demo_5 {
public static void main(String[] args) {
FileReader fr=null; //文件取出字符流对象(输入流)
FileWriter fw=null; //写入到文件(输出流)
try {
fr=new FileReader("e:\\test.txt"); //创建一个fr对象
fw=new FileWriter("d:\\test.txt"); //创建输出对象
char []c=new char[1024]; //读入到内存
int n=0; //记录实际读取到的字符数
while((n=fr.read(c))!=-1){
//String s=new String(c,0,n);
fw.write(c,0,n);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
fr.close();
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
打开D盘的test.txt文件,出现相同的字符串。
案例2:为了提高效率引入了缓冲字符流
依然实现读取一个文件并写入到另一个文件中,直接操作String。
public class Demo_6 {
public static void main(String[] args) {
BufferedReader br=null;
BufferedWriter bw=null;
try{
FileReader fr=new FileReader("e:\\test.txt"); //先创建FileReader对象
br=new BufferedReader(fr);
FileWriter fw=new FileWriter("d:\\test1.txt"); //创建FileWriter对象
bw=new BufferedWriter(fw);
String s="";
while((s=br.readLine())!=null){ //循环读取文件,s不为空即还未读完毕
bw.write(s+"\r\n"); //输出到磁盘,加上“\r\n”为了实现换行
}
}catch(Exception e){
e.printStackTrace();
}finally{
try {
br.close();
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
打开D盘的test1.txt文件,出现相同的字符串。
总结:字节流操作对象byte,字符流操作对象char,缓冲字符流操作对象String。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。