栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

Java------IO流

Java------IO流

IO流的分类:
    流向:
        输入流 读取数据
        输出流 写出数据
    数据类型:
        字节流
            字节输入流 读取数据 InputStream
            字节输出流 写出数据 OutputStream
(是一个抽象类,不能被实例化,需要找一个具体的子类FileOutStream)
构造方法:
    FileOutputStream(File file) 创建文件输出流以写入由指定的 File对象表示的文件。
    FileOutputStream(String name) 创建文件输出流以指定的名称写入文件。

        字符流
            字符输入流 读取数据 Reader
            字符输出流 写出数据 Writer
字节输出流的操作步骤:
 1、创建字节输出流对象
 2、调用方法,写数据
 3、释放资源
public class FileOutputStreamDemo1 {
    public static void main(String[] args) throws Exception{
        //创建字节流输出对象
        //FileOutputStream(File file) 创建文件输出流以写入由指定的 File对象表示的文件。
//        File file = new File("b.txt");
//        //如果目标文件不存在,自动创建
//        FileOutputStream fos = new FileOutputStream(file);
        //FileOutputStream(String name) 创建文件输出流以指定的名称写入文件。
        //如果目标文件不存在,自动创建
        FileOutputStream fos = new FileOutputStream("c.txt");
//        System.out.println(fos);

        //调用方法,写数据
        fos.write("大数据,yyds".getBytes());

        //释放资源
        //close()关闭此文件输出流并释放与此流相关联的任何系统资源。
        fos.close();

        fos.write("继续写入".getBytes());




    }
}
字节输出流写数据的几种方法:
    public void write(int b)
    public void write(byte[] b)
    public void write(byte[] b,int off,int len)
public class FileOutputStreamDemo2 {
    public static void main(String[] args) throws Exception{
        //创建字节输出流对象
        FileOutputStream fos = new FileOutputStream("d.txt");

        //public void write(int b)
        //97,底层存储的二进制,97对应的ASCII码的字符是a
        fos.write(97);//在文件里输入对应的ASCII码值
        fos.write(48);
        fos.write(65);

        //public void write(byte[] b)
        byte[] byts = {97,98,99,100,101};
        fos.write(byts);

        //public void write(byte[] b,int off,int len)
        //从位于偏移量 off的指定字节数组写入 len字节到该文件输出流。
        fos.write(byts,1,3);//数组下标从0开始故98,99,100对应的BCD




        //释放资源
        fos.close();
    }
}

输出结果:

如何实现换行呢?
    要想知道为什么没有实现换行?因为我们只写入了数据的字节,并没有写入换行符
    如何实现呢?在写字节的时候,添加一个换行符,注意:不同的系统,换行符不一定一样
    Mac: r
    Windows: rn
    Linux: n
public class FileOutputStreamDemo3 {
    public static void main(String[] args) throws Exception {
        //创建字节输出流对象
//        FileOutputStream fos = new FileOutputStream("e.txt");
//        fos.write("大数据1,yyds".getBytes());
//        fos.write("rn".getBytes());
//        fos.write("大数据2,yyds".getBytes());

        //FileOutputStream(String name, boolean append)
        //创建文件输出流以指定的名称写入文件。
        //true表示的是可以追加写入数据
        FileOutputStream fos = new FileOutputStream("e.txt", true);
        fos.write("rn今天下雪了rn".getBytes());
//        fos.write("rn".getBytes());
        fos.write("但是没有看到积雪".getBytes());


        //释放资源
        fos.close();
        //....
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/741992.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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