java中流的简单小结

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.纯文本可以用字符流读取,其余全部用字节流读取。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值