一、BufferedReader(读,输入流)
理解:带缓冲的流
1.FileInputStream属于InputStream
2.InputStreamReader传入的参数应该是InputStream,且InputStreamReader属于Reader类
3.BufferedReader应该传入Reader类。
4.可以写成:
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
范例:
public class Test02 {
public static void main(String[] args) {
/*
* 1.读数据:Input
* */
File file = new File("d://456.txt");
try {
FileInputStream fis = new FileInputStream(file); //读字节
InputStreamReader isr = new InputStreamReader(fis); //读字符
BufferedReader br = new BufferedReader(isr);//读一行
String line = br.readLine(); //产生IOException异常
while(line!=null)
{
System.out.println(line);
line = br.readLine();
}
br.close(); //可以值关闭br流,其他的流都会关闭
isr.close();
fis.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
注:BufferedReader中的readLine方法当读到末尾时,返回null;
读字节流时num = fis.read(byte[] arr),当读到末尾时返回的是-1.
二、BufferedWriter(写入,输出流)
/*
利用缓冲写入文字—-BufferedWriter:
1.写入一定要flush();读出不用
*/
File file1 = new File("d://a.txt");
try {
FileOutputStream fos = new FileOutputStream(file1);
OutputStreamWriter osw = new OutputStreamWriter(fos);
BufferedWriter bw = new BufferedWriter(osw);
bw.write("sjkaueiwque"); //有IOException异常
bw.flush();
bw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
三、拷贝文件
/*要求:将d://a.txt文件中的内容拷贝到d://12.txt
分析:
1.a.txt建立输入流,d://12.txt建立输出流
2.建字节流,循环读入a.txt中字节,并写入到d://12.txt中。flush()
注:由于存在编码问题,这里拷贝一般用字节流的方式,因为字节拷贝时不会变的。
*/
public class Test03 {
public static void main(String[] args) {
File files = new File("d://a.txt");
File filec = new File("d://12.txt");
try {
FileInputStream fiss = new FileInputStream(files);
FileOutputStream fosc = new FileOutputStream(filec);
byte[] arr = new byte[1024];
int num = fiss.read(arr); //有IOException异常
while(num!=-1)
{
fosc.write(arr, 0, num);
num = fiss.read(arr);
}
fosc.flush();
fosc.close();
fiss.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
解析:
1.当用BufferedWriter写入时:
bw.write();
bw.newLine(); //需要重起一行
2.这里用的字节流,不用newLine方法,因为\n也可以读出来。