/*
字符流
Reader
Writer--FileWriter
字符流缓冲区:提高流操作效率
BufferedReader
BufferedWriter
*/
package pack;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.LineNumberReader;
public class Main {
public static void sys(Object obj) {
System.out.println(obj);
}
public static void main(String[] args) throws Exception{
//method1();//FileWriter
//method2();//FileWriter
//method3();//FileReader
//method4();//拷贝文件
//method5();//BufferedWriter
//method6();//FileReader
//method7();//拷贝文件
method8();//LineNumberReader加序号功能
}
public static void method1() throws Exception {
FileWriter fw = new FileWriter("E:\\1.txt");
fw.write("abc"); //将字符串写入流中
fw.flush(); //刷新流对象中的缓冲中的数据
fw.close(); //关资源
}
public static void method2() throws Exception {
FileWriter fw = new FileWriter("E:\\1.txt",true);//不覆盖存在的文件
fw.write("cc\r\nc"); //换行
fw.flush();
fw.close();
}
public static void method3() throws Exception {
FileReader fr = new FileReader("E:\\1.txt");
/*int ch = 0;
while((ch=fr.read())!=-1) {
sys((char)ch);
}*/
/*char[] buf = new char[9];
int ch = fr.read(buf);//写入数组中,ch为读到的个数
sys(new String(buf));//输出数组*/
char[] buf = new char[3];
int num = 0;
while((num=fr.read(buf))!=-1) //个数不是-1
sys(new String(buf,0,num));//从0到num
fr.close();
}
/*拷贝文件*/
public static void method4() throws Exception {
/*FileReader fr = new FileReader("E:\\1.txt");
FileWriter fw = new FileWriter("E:\\2.txt");
int ch = 0;
while((ch=fr.read())!=-1)
fw.write(ch);
fr.close();
fw.close();*/
FileReader fr = new FileReader("E:\\1.txt");
FileWriter fw = new FileWriter("E:\\2.txt");
char[] buf = new char[1024];
int len = 0;
while((len=fr.read(buf))!=-1)
fw.write(buf,0,len);
fw.close();
fr.close();
}
public static void method5() throws Exception {
/*缓冲区是为了提高效率,得先有流*/
FileWriter fw = new FileWriter("E:\\1.txt");
BufferedWriter bufw = new BufferedWriter(fw);
bufw.write("kk");
bufw.newLine(); //写入换行符
bufw.write("gg");
bufw.flush();
bufw.close();//关闭缓冲区就是关闭缓冲区作用的流对象
}
public static void method6() throws Exception {
FileReader fr = new FileReader("E:\\1.txt");
BufferedReader bufr = new BufferedReader(fr);
String line = null;
while((line=bufr.readLine())!=null)//返回空表示读到末尾
sys(line);
bufr.close();
}
/*拷贝文件*/
public static void method7() throws Exception {
BufferedReader bufr = new BufferedReader(new FileReader("E:\\1.txt"));
BufferedWriter bufw = new BufferedWriter(new FileWriter("E:\\2.txt"));
String line = null;
while((line=bufr.readLine())!=null)
bufw.write(line);
bufr.close();
bufw.close();
}
public static void method8() throws Exception {
FileReader fr = new FileReader("E:\\1.txt");
LineNumberReader lnr = new LineNumberReader(fr);
String line = null;
while((line=lnr.readLine())!=null)
sys(lnr.getLineNumber()+":"+line);
lnr.close();
}
}
原文地址:http://blog.csdn.net/sjtu_chenchen/article/details/45505885