1.流的分类

    按字节流分: InputStream(输出流)     OutputStream(输入流)
    按字符流分: Reader  Writer
    其他分类: 缓冲流、文件流、对象流等
 提示:输入、输出是站在程序的角度而言,所有输入流是“读取”,所有输出流是“写入”。

2.转换流(将字节流转换为字符流

  InputStreamReader: 2个参数,第一个参数InputStream,第二个参数指定编码“UTF-8”

       OutputStreamWriter:2个参数,第一个参数OutputStream,第二个参数指定编码“UTF-8”

3.缓冲流

  BufferedReader: 参数为InputStreamReader类型

  PrintWriter: 第一个参数为OutputStreamWriter类型,第二个参数“true"表示直接push到程序中

4.写入实例

    /**
     * 书写文件内容
     */
    public static void writeWord(String str) throws IOException {
        try (
                FileOutputStream fileOutputStream = new FileOutputStream(URLDecoder.decode(path, "UTF-8")+"static\\system.txt");
//                FileOutputStream fileOutputStream = new FileOutputStream("/usr/java/myfile/system.txt");
                OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream,"UTF-8");
                PrintWriter out = new PrintWriter(outputStreamWriter);
                ){
            out.write(str);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

 

5.读取实例

  

 /**
     * 读取文件内容
     */
    public  static String readWord ()  {
        try (    
                FileInputStream  fileInputStream = new FileInputStream(URLDecoder.decode(path, "UTF-8")+"static\\system.txt");
//                FileInputStream  fileInputStream = new FileInputStream("/usr/java/myfile/system.txt");
                InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,"UTF-8");
                BufferedReader br = new BufferedReader(inputStreamReader);
                ){
            String line = null;
            StringBuffer sBuffer = new StringBuffer();
            while((line = br.readLine())!=null){
                sBuffer.append(line);
            }
            return sBuffer.toString();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } 
    }
    

 

提示:1.java7以上,可以将流直接定义在try的小括号中,这样可以不用手动去关闭流。

   2.纯文本可以用字符流读取,其余全部用字节流读取。
posted on 2018-12-03 15:34  蓝色恋人  阅读(186)  评论(0编辑  收藏  举报