栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

IO字符流

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

IO字符流

  1. 字符流

java IO提供了两类流,按读写信息的内容分为

  • 字节流: InputStream,OutputStream. 读写的内容以字节为单位。
  • 字符流: Reader,Writer。 读写的内容以字符为单位。
  • 转换流:是一组高级流,能够将字节流转换成字符流。

输出字符转入文件

public class OWSDemo {
    public static void main(String[] args) throws IOException {
        FileOutputStream fos = new FileOutputStream("osw.txt");

        OutputStreamWriter osw = new OutputStreamWriter(fos,"utf-8");
        String s = "not found anything";

        
        osw.write(s);
        osw.close();
    }
}

显示文件内内容

public class ISRDemo {
    public static void main(String[] args) throws IOException {
        FileInputStream fis = new FileInputStream("osw.txt");

        InputStreamReader isr = new InputStreamReader(fis,"utf-8");

        int d;

        while ((d=isr.read())!=-1){
            System.out.print((char) d);
        }
        System.out.println("over");
        isr.close();

    }
}
  1. 缓冲字符流
  • 缓冲字符流
    java.io.BufferedWriter
    java.io.BufferedReader
    使用缓冲对文件的内容进行块读写,提高读写效率

  • java.io.PrintWriter
    是BufferedWrite基础上的又一次加工
    具有自动刷新换行的功能


public class PwDemo {
    public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
        PrintWriter pw = new PrintWriter("pwd.txt","utf-8");

        pw.println("像我这样优秀的人");
        pw.write("is a hero");
        System.out.println("over");

        pw.close();
    }
}

高级流由低级流转换,下面是转换过程

FileOutputStream fos = new FileOutputStream("pw.txt");
OutputStreamWriter osw = new OutputStreamWriter(fos,"utf-8");
BufferedWriter bw = new BufferedWriter(osw);
PrintWriter pw = new PrintWriter(bw);

pw.println("解决");
pw.close();
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/337951.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号