Java-IoStream详解(举例+代码)-妈妈再也不用担心我分不清流了

1,概述

Java 中的 IO 流可以分为两大类:字节流(Byte Stream)和字符流(Character Stream)。每个类别又可以进一步分为输入流(InputStream)和输出流(OutputStream),以及读取器(Reader)和写入器(Writer)。
在这里插入图片描述

2,字节流

2.1,字节输出流(FileOutputStream)

* 演示:字节输出流FileOutputStream
* 实现需求:写一段文字到本地文件中
*
* 实现步骤:
*        创建对象
*           细节1:参数是字符串表示的路径或者File对象都是可以的
*           细节2:如果文件不存在会创建一个新的文件,但要保证父级文件存在
*           细节3:如果文件已经存在,会清空文件
*        写出数据
*           细节1:write方法参数是整数,实际是写入的是整数在ASCII对应的字符
*        释放资源
*           每次使用完流之后都会释放资源
package IoStream.fileoutputstream;

import java.io.FileOutputStream;
import java.io.IOException;

public class demo1
{
   
    public static void main(String[] args) throws IOException
    {
   
        //1,创建对象-建立程序与文件的通道
        FileOutputStream fileOutputStream = new FileOutputStream("src/IoStream/a.txt");
        //2,写出数据
        fileOutputStream.write(97);
        fileOutputStream.close();
    }
}

FileOutputStream写数据的三种方式
* void write(int b)----->一次写一个字节数据
* void write(byte b)----->一 次写一个字节数组数据
* void write(byte b,int off ,int len)---->一次写一个字节数组的部分数据
*           参数1:数组
*           参数2:起始索引
*           参数3:写入个数
package IoStream.fileoutputstream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class demo2
{
   
    public static void main(String[] args) throws IOException
    {
   
        //1,创建对象
        FileOutputStream fileOutputStream = new FileOutputStream(new File(".\\src\\IoStream\\FileStream\\a.txt"));
        //2,写出数据-1
        fileOutputStream.write(97);
        fileOutputStream.write(98);
        //fileOutputStream.close();
        //2,写出数据-2
        byte[] bytes = {
   97,98,99,100,101,102};
        fileOutputStream.write(bytes);
        //2,写出数据-3
        fileOutputStream.write(bytes,1,2);
        fileOutputStream.close();
    }
}

    数据写出
    //1,如何换行写数据?
    //2,打开文件如何不清空原始数据?
package IoStream.fileoutputstream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class demo3
{
   
    //数据写出
        //1,如何换行写数据?
        //2,打开文件如何不清空原始数据?
    public static void main(String[] args) throws IOException
    {
   
        //创建对象
        FileOutputStream fileOutputStream = new FileOutputStream(".\\a.txt",true);//打开续写功能
        //写出数据
        String str = "horty";
        byte[] bytes = str.getBytes();
        fileOutputStream.write(bytes);

        String str1 = "\r\n";//写入换行
        byte[] bytes2 = str1.getBytes();
        fileOutputStream.write(bytes2);

        String str2 = "33114";
        byte[] bytes3 = str2.getBytes
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值