IO流详解(二)字节流

来源:互联网 发布:模拟硬盘录像机 该网络 编辑:程序博客网 时间:2024/06/09 18:25

第一讲地址:http://blog.csdn.net/qq_25448409/article/details/73527375

上一章讲述了操作文本文件的流对象字符流,这一讲来介绍字节流。计算机里面所有的东西都是二进制,所有我们可以通过字节流操作任何格式文件,比如MP3,图片,视频等。虽然字节流可以操作所有格式的文件,但是如果要操作文字数据,优先考虑字符流。 字节流的命名也很巧妙啊,比如上一节提到的,以reader和writer结尾的都是字符流。为什么,因为操作的是字符,我们都是看的懂的,所以我们可以‘reader’和‘writer’, 但是这一节我们操作的是字节,都是二进制,我们当然看不懂,看不懂当然就不能‘reader’和‘writer’。 只能通过InputStream和OutputStream流来接收。


FileOutputStream

测试字节输出流,把一句话存储到一个文本文件中。 通过这个例子我们就可以验证那个理论:计算机里面所有的东西都是二进制,所有我们可以通过字节流操作任何格式文件。
public class FileOutputStreamDemo {public static void main(String[] args) throws IOException {//1,创建字节输出流对象。用于操作文件.FileOutputStream fos = new FileOutputStream("bytedemo.txt");//2,写数据。直接写入到了目的地中,不需要进行临时存储。 fos.write("你好".getBytes());//fos.flush();fos.close();//关闭资源动作要完成。 }}

FileInputStream

这次我们把这个文件读取出来,在这里要注意我注释中的话,read()是一次读取一个字节,如果文本里面是英文没问题。如果是中文那就会出现乱码,因为中文占两个字节。
public class FileInputStreamDemo {public static void main(String[] args) throws IOException {//1,创建一个读取流对象。和指定文件关联。FileInputStream fis = new FileInputStream("bytedemo.txt");byte[] buf = new byte[1024];int len = 0;while ( (len = fis.read(buf)) != -1) {System.out.println(new String(buf, 0, len));}/** * read()一次读取一个字节,如果文本里面是英文没问题, * 如果是中文那就会出现乱码,如果是字符流,那么一次就能把这个中文读出来 *  * 而字节流得要读两次,因为中文占两个字节 *  * int ch = fis.read(); * System.out.println(ch); *  * ============================= *  * int ch = 0; * while ( (ch = fis.read()) != -1) { * System.out.print((char)ch); * } */fis.close();}}

拷贝一个Mp3

操作文本肯定也腻了,不能体现出字节流的威力。为了掩饰字节流的特性,我们来做一个拷贝文件的练习,提供了三种方法。第一种用jdk提供的缓冲区,这种方法无疑是最快的,关于缓冲是什么上一节讲过。
public class CopyMp3 {public static void main(String[] args) throws IOException {copy_3();}/** * jdk提供的缓冲区 * @throws IOException */public static void copy_1() throws IOException {FileInputStream fis = new FileInputStream("d:\\a.mp3");BufferedInputStream bis = new BufferedInputStream(fis);FileOutputStream fos = new FileOutputStream("e:\\b.mp3");BufferedOutputStream bos = new BufferedOutputStream(fos);int ch = 0;while ( (ch = bis.read()) != -1) {bos.write(ch);}bos.close();bis.close();}/** * 自定义缓冲区 * @throws IOException */public static void copy_2() throws IOException {FileInputStream fis = new FileInputStream("d:\\a.mp3");FileOutputStream fos = new FileOutputStream("e:\\b.mp3");byte[] buf = new byte[1024];while ( (fis.read(buf)) != -1) {fos.write(buf);}fos.close();fis.close();}/** * fis.available()获取文本的大小然后创建一个和源文件相同大小的字节数据 * 不过不建议,如果文件过大创建数组会很慢 * @throws IOException */public static void copy_3() throws IOException {FileInputStream fis = new FileInputStream("d:\\a.mp3");FileOutputStream fos = new FileOutputStream("e:\\b.mp3");byte[] buf = new byte[fis.available()];fis.read(buf);fos.write(buf);fos.close();fis.close();}}



原创粉丝点击