Java 中 字节流 和 字符流的区别(转自郝斌 Java 教学)

来源:互联网 发布:数据漫游是什么意思 编辑:程序博客网 时间:2024/05/16 11:22

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

总之呢 

复制就使用 字节流

显示输出就使用 字节流

先理解这么多 不对之处 轻拍

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////



/*

2009年7月3日10:43:18
本程序证明了:
通过字符流无法完成非文本文件的复制
或者说:
字符流只能处理文本文件
不能处理非文本文件


*/


import java.io.*;


public class TestFileReaderWriterCopy_2
{
public static void main(String[] args) throws Exception
{
FileReader fr = new FileReader("E:\\IBM教学\\java\\lesson_io\\妹妹来看我.mp3");
FileWriter fw = new FileWriter("d:/zhangsan.haha");
int ch;

ch = fr.read();
while (-1 != ch)
{
fw.write(ch);
ch = fr.read();
}
fw.flush();

fr.close();
fw.close();
}

}


/*
2009年7月3日10:44:37
本程序证明了:
通过字节流可以完成音频格式文件的复制
实际上我们通过字节流可以完成任意格式文件的复制

但本程序有个缺点:
没有缓冲区, 处理速度慢

可以参考对比"TestInputStreamOutputStreamCopy_3.java"

*/


import java.io.*;


public class TestInputStreamOutputStreamCopy
{
public static void main(String[] args) throws Exception
{
FileInputStream fr = new FileInputStream("E:\\IBM教学\\java\\lesson_io\\妹妹来看我.mp3");
FileOutputStream fw = new FileOutputStream("d:/zhangsan.haha");
int ch;

ch = fr.read();
while (-1 != ch)
{
fw.write(ch);
ch = fr.read();
}
fw.flush();

fr.close();
fw.close();
}
}



/*
2009年7月3日10:47:37
本程序证明了:
通过字节流可以完成图像文件的复制
实际上我们通过字节流可以完成任意格式文件的复制

*/


import java.io.*;


public class TestInputStreamOutputStreamCopy_2
{
public static void main(String[] args) throws Exception
{
FileInputStream fr = new FileInputStream("C:\\1.jpg");
FileOutputStream fw = new FileOutputStream("d:/zhangsan.haha");
int ch;

ch = fr.read();
while (-1 != ch)
{
fw.write(ch);
ch = fr.read();
}
fw.flush();

fr.close();
fw.close();
}
}



/*
2009年7月3日10:45:49
本程序证明了:
带缓冲区的字节流处理文件的速度要快于不带缓冲区的字节流处理文件的速度

可以参考对比"TestInputStreamOutputStreamCopy.java"

*/


import java.io.*;


public class TestInputStreamOutputStreamCopy_3
{
public static void main(String[] args) throws Exception
{
BufferedInputStream bis = new BufferedInputStream( new FileInputStream("E:\\IBM教学\\java\\lesson_io\\妹妹来看我.mp3"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("d:/zhangsan.haha"));
byte[] buf = new byte[1024];
int len;

len = bis.read(buf);
while (-1 != len)
{
bos.write(buf, 0, len);
len = bis.read(buf);
}
bos.flush();

bos.close();
bis.close();
}
}

0 0
原创粉丝点击