• 字符输入流


    原因:使用字节流读取中文会产生乱码,使用GBK编码的中文占用两个字节。使用UTF-8编码的字符占用3个字节。

      我们动手操作一下,在test.txt中存入汉字“你好大白”使用字节输入流进行读。

    @Test
    public void testReader() throws IOException {
            InputStream is = new FileInputStream("F:/test.txt");
            int b;
            while((b=is.read())!=-1){
                System.out.print(b);
                System.out.print((char)b);
            }
            return ;
    }
    
    结果:228ä189½160229å165¥189½229å164¤167§231ç153™189½

    java.io.Reader,字符输入流,是字符输入流最顶层的父类,定义了一些共性的成员方法,是一个抽象类。字符流一次可以读取一个字符,字节流一次可以读取一个字节。

    我们在用字符流进行读写

    @Test
        public void testReader() throws IOException {
            FileReader fileReader = new FileReader("f:/test.txt");
            int len;
            while((len = fileReader.read())!=-1){
                System.out.print(len);
                System.out.print((char)len);
            }
        }
    20320你22909好22823大30333白102f103g103g50235#35#35#

    java.io.Writer,字符输出流,是字符输出流最顶层的父类,定义了一些共性的成员方法,是一个抽象类。字符流一次可以读取一个字符,字节流一次可以读取一个字节。

      writer写字符的过程:1.写字符串2.写字符串的部分3.写字符4.写字符数组5.写字符的数组的部分。

    Writer append​(char c)
    Appends the specified character to this writer.
    Writer append​(CharSequence csq)
    Appends the specified character sequence to this writer.
    Writer append​(CharSequence csq, int start, int end)
    Appends a subsequence of the specified character sequence to this writer.
    abstract void close()
    Closes the stream, flushing it first.
    abstract void flush()
    Flushes the stream.
    static Writer nullWriter()
    Returns a new Writer which discards all characters.
    void write​(char[] cbuf)
    Writes an array of characters.
    abstract void write​(char[] cbuf, int off, int len)
    Writes a portion of an array of characters.
    void write​(int c)
    Writes a single character.
    void write​(String str)
    Writes a string.
    void write​(String str, int off, int len)
    Writes a portion of a string.

        字符输出流的使用步骤:

          1.创建FileWriter对象,构造方法中绑定要写入数据的目的地。

          2.使用FileWriter对象中的方法write,把数据写入到内存缓冲区(字符转换成字节的过程)

          3.使用FileWriter对象中的方法flush,把内存缓冲区的数据,刷新到文件中

          4.释放资源(先把内存缓冲区中的数据刷新到文件中

      字符串的追加和换行:

        Windows:

        Linux:/n

        mac:/r

            

     

    呵呵
  • 相关阅读:
    array_flip
    qy Undefied index报错
    strip_tag
    query使用
    tp5 sql 大于小于
    OfficeTools.OnlineEditWord
    OCX控件打包成CAB并实现数字签名过程
    使用css技术代替传统的frame技术
    delphi常用函数和方法
    js正则表达使用实例
  • 原文地址:https://www.cnblogs.com/jiazhiyuan/p/12272116.html
Copyright © 2020-2023  润新知