zoukankan      html  css  js  c++  java
  • 字节流和字符流

    在整个IO包中,流的操作就分为两种:

    字节流:字节输出流OutputStream,字节输入流InputStream

    字符流(一个字符等于两个字节):字符输出流Writer,字符输入流是Reader

    IO操作的基本步骤

    1,使用File找到一个文件

    2,使用字节流和字符流的子类为OutputStream,InputStream,Writer,Reader进行实例化操作

    3,进行读或写操作

    4,关闭:close(),在流的操作中最终必须进行关闭

    在java中"\r\n"表示换行

    字节输出输入

    import java.io.*;

    public class OutputStreamDemo {

    public static void main(String args[]) throws IOException

    {

     //写入数据

     File file=new File("d:"+File.separator+"demo.txt");

     OutputStream out=new FileOutputStream(file,true);//在文件后追加

     String str="hello world";

     byte b[]=str.getBytes();

     out.write(b);

     out.close();

     //读取数据

     File file1=new File("d:"+File.separator+"demo.txt");

     InputStream in=new FileInputStream(file1);

     byte[] by=new byte[(int)file.length()];//根据文件大小开辟字节空间

     in.read(by);

     System.out.println(by.toString());

    }

    }

    字符输出输入
    import java.io.*;
    public class WriterDemo {
    public static void main(String args[]) throws IOException
    {
    //字符写入
    File file=new File("d:"+File.separator+"demo.txt");
    Writer writer=new FileWriter(file);
       String str="hello world!";
       writer.write(str);
       writer.close();
       //字符读取
       File file1=new File("d:"+File.separator+"demo.txt");
            Reader read=new FileReader(file1);
            char[] ch=new char[(int)file1.length()];
            read.read(ch, 0, (int) file1.length());
            System.out.println(ch.toString());
            read.close();
    }
    }
    字节流在操作的时候是直接与文件本身关联,不使用缓冲区,字节直接存到文件中;字符流在操作的时候是通过缓冲区与文件操作,字符到缓冲区然后再到文件中,所以字符流中存在一个flush()方法来刷新缓冲区。
    综合比较来讲,在传输或者在硬盘上保存的内容是以字节的形式存在的,所以字节流的操作较多,但是在操作中文的时候字符流比较好用。

  • 相关阅读:
    Introduction to PostGIS 之加载shp数据
    缺陷管理总结篇
    对lIKE语句的优化
    数据库查询优化
    如何在 32 位版本的 ASP.NET 1.1 和 64 位版本的 ASP.NET 2.0 之间切换
    加载启动目录以外的DLL(Assembley)的3种方法
    C#中使用windows medie player控件
    在Asp.net中使用多线程
    编程控制windows防火墙的exception list.
    读书笔记Win32多线程程序设计(1)
  • 原文地址:https://www.cnblogs.com/jinzhengquan/p/1947973.html
Copyright © 2011-2022 走看看