测试各种流的包装、读写及转换
/**
* 测试各种流的包装、读写及转换
* */
public class TestFlowReadAndWrite {
/**测试字节输入流
* @throws IOException */
public void testByteFlowRead() throws IOException{
FileInputStream fis = new FileInputStream("F:/test.bmp");
/**Buffer管子是套在File管子之上的*/
BufferedInputStream bis = new BufferedInputStream(fis);
int b = -1;
// fis.read()依次读取字节数据,读取结束时返回 -1
while ((b = bis.read()) != -1) {
System.out.println(b);
}
/**调用外面的管子的close()方法后,将依次调用里面管子的close()方法,依次由里而外的close()*/
bis.close();
}
/**测试字符输出流
* @throws IOException */
public void testByteWrite() throws IOException{
FileOutputStream fos = new FileOutputStream("F:/test32.bmp");
BufferedOutputStream bos = new BufferedOutputStream(fos);
// fis.read()依次读取字节数据,读取结束时返回 -1
bos.write(12);
/**调用外面的管子的close()方法后,将依次调用里面管子的close()方法,依次由里而外的close()*/
bos.close();
}
/**测试字节流读写*/
public void testByteFlow() throws IOException{
/**读取某文件并写入另一文件*/
FileInputStream fis = new FileInputStream("F:/test.bmp");
FileOutputStream fos = new FileOutputStream("F:/test32.bmp");
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int b = -1;
// fis.read()依次读取字节数据,读取结束时返回 -1
while ((b = bis.read()) != -1) {
bos.write(b);
// System.out.println(b);
}
/**调用外面的管子的close()方法后,将依次调用里面管子的close()方法,依次由里而外的close()*/
bis.close();
bos.close();
}
/**测试字符流读
* @throws IOException */
public void testCharsFlowRead() throws IOException{
/**因读取文本,因此,直接使用字符流*/
FileReader fr = new FileReader("F://hello.txt");
BufferedReader br = new BufferedReader(fr);
String str = null;
while((str = br.readLine())!= null){//一次输出文本中的一行内容
System.out.println(str);
}
br.close();
}
/**测试字符流写
* @throws IOException */
public void testCharsFlowWrite() throws IOException{
FileWriter fw = new FileWriter("F:/tt.txt");
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
pw.write("hello world");
pw.close();
}
/**测试转换流(将字节流转换为字符流)
* @throws IOException */
public void testTransForm() throws IOException{
//将字节流转换为字符流输出
FileInputStream fis = new FileInputStream("F:/test.bmp");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
String str = null;
while((str = br.readLine())!= null){//一次输出文本中的一行内容
System.out.println(str);
}
//将字符流转换为字符流写入
FileOutputStream fos = new FileOutputStream("F:/fuck.txt");
OutputStreamWriter osw = new OutputStreamWriter(fos,"UTF-8");
BufferedWriter bw = new BufferedWriter(osw);
PrintWriter pw = new PrintWriter(bw);
pw.write("hello world");
pw.close();
}
}
注:
使用Java各种流类,在用完后一定要显示地关闭(调用close()方法)。
1.当有多个流泪层层包装时,在关闭流类时只需要关闭最外层的流类(当关闭最外层流类时,系统会自动地由里至外一次关闭流类)
2.如果使用输出类时没有显示关闭流类,会造成输出不完整。比如输出是向文件写入的话,那么文件的内容会写入不完整(剩余部分保存在缓冲流内,调用close()方法前会自动调用flush()方法将缓存在缓冲流中的数据全部冲洗干净(也就是全部输出缓冲结果))
调用close()方法可以只调用最外层的流类(最外层的流类一般是各种包装类,当关闭最外层流类时,如果该类会自动调用flush()方法)
比如在使用缓冲输出流写文件时,如果不关闭输出流会造成文件的内容写入不完整(剩余部分保存在缓冲流内)