JAVA- character stream

Jifuryu:

  • Character output streams: Writer, the operation of the document subclass: FileWriter
  • Character-input stream: Reader, operating subclass of the document: FileReader
  • Each operating unit is a character
  • File character stream operations will own cache, the default size is 1024 bytes, after the cache is full or manually refresh the cache, or will close the stream when writing data to files
  • How to choose a byte stream or character stream:
  • General Procedure when non-text files, with a byte stream, a text file operation, it is recommended to use the character stream
  • Internal byte stream or a byte stream to achieve

Examples

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

public class CharStreamDemo {

    public static void main(String[] args) {
        out();
        in();

    }
//字符输出流
    public static void out() {
        //确定目标文件
        File file=new File("/Users/a10.11.5/test/123.txt");     
        try {
            //构建文件输出流
            Writer out=new FileWriter(file,true);
            //输出内容
            out.write(",村花到我家");
            //结束流
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
//字符输入流
    public static void in() {
        //确定目标文件
        File file=new File("/Users/a10.11.5/test/123.txt");     
        try {
            //创建文件入流
            Reader in =new FileReader(file);
            char[]cs=new char[1];
            int len = -1;
            StringBuilder buf=new StringBuilder();
            while ((len=in.read(cs))!=-1) {
                buf.append(cs,0,len);
            }
            System.out.println(buf);
            //结束流
            in.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

Guess you like

Origin blog.csdn.net/weixin_33810302/article/details/90985276