IO流(完善中)

1.基本概念

1.1 什么是IO流

I:input(输入)

O:output(输出)

流:stream

IO流是存储和读取数据的解决方案。程序控制流。

1.2 IO流的作用

读取数据(本地读到网络,网络读到本地)

1.3 IO流类别

1.3.1 根据流向区别

输入流:InputStream,本地数据读到程序中

输出流:OutputStream,程序数据读到本地

1.3.2 根据处理数据的方式

字节流:操作所有类型文件

字符流:只能操作纯文本文件(windows记事本可以正常打开不乱码)

2.文件输出流(FileOutputStream)

2.1 步骤

2.1.1 创建对象

创建文件输出流对象,参数可以是绝对路径或者文件。

当前文件存在,就清空再写入。

当前文件不存在,就新建。

2.1.2 写出数据

writer方法参数是整数,实际是整数在ASCII对应的字符。

2.1.3 释放资源

每次写完之后需要释放资源。

2.2 一次输出一个字符

public static void main(String[] args) throws IOException {
    //1.创建对象
    FileOutputStream fop = new FileOutputStream("D:\\ideaProject\\IoPractice\\src\\main\\java\\cn\\file\\output\\demo01.txt");
    //2.写出数据
    fop.write(98);
    //3.关闭流
    fop.close();
}

2.3 一次输出一个字符数组

public static void main(String[] args) throws IOException {
    //1.创建对象
    FileOutputStream fop = new FileOutputStream("D:\\ideaProject\\IoPractice\\src\\main\\java\\cn\\file\\output\\demo02.txt");
    //2.写出数据
    byte[] b={97,98,99,100};
    fop.write(b);
    //3.关闭流
    fop.close();
}

2.3 一次输出一个数组,可控制从哪个索引开始,输入几个字符

public static void main(String[] args) throws IOException {
    //1.创建对象
    FileOutputStream fop = new FileOutputStream("D:\\ideaProject\\IoPractice\\src\\main\\java\\cn\\file\\output\\demo03.txt");
    //2.写出数据
    byte[] b={97,98,99,100};
    fop.write(b,0,3);
    //3.关闭流
    fop.close();
}

2.4 续写

public static void main(String[] args) throws IOException {
    //1.创建对象
    FileOutputStream fop = new FileOutputStream("D:\\ideaProject\\IoPractice\\src\\main\\java\\cn\\file\\output\\demo04.txt",true);
    //2.写出数据
    byte[] b={97,98,99,100};
    fop.write(b,0,3);
    //3.关闭流
    fop.close();
}

2.5 换行

public static void main(String[] args) throws IOException {
    //1.创建对象
    FileOutputStream fop = new FileOutputStream("D:\\ideaProject\\IoPractice\\src\\main\\java\\cn\\file\\output\\demo05.txt");
    //2.写出数据
    String s1= "123wer345";
    byte[] bytes1 = s1.getBytes();
    fop.write(bytes1);
    String s2 ="\r\n";
    byte[] bytes2 = s2.getBytes();
    fop.write(bytes2);
    fop.write(bytes1);
    //3.关闭流
    fop.close();
}

  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值