java IO流

目录

1、简介

2、应用实例

(1)实例一个File对象创建新的文件,通过FileWriter对文件写入,在使用FileReader对文件读取。

(2)FileOutputStream写入,FileInputStream读取。


1、简介

(1)java io 是表示数据输入输出操作。IO是int\out缩写,Stream表示流。

(2)按照功能可分为输入流、输出流。

(3)按单元分类有字节流、字符流。

  InputStream:字节输入流;

  OutputStream:字节输出流;

  FileWriter:字符输出流;

  FileReader:字符输入流;

(4)应用场景:当我们需要对数据流进行解析处理时,可采用字符流;当处理文件是音频或者视频文件时应该采用字节流。字符流底层实现仍是字节流

 

2、应用实例

(1)实例一个File对象创建新的文件,通过FileWriter对文件写入,在使用FileReader对文件读取。

public static void main(String[] args) throws IOException {
    String string="D:\\txt_file"+"\\"+new SimpleDateFormat("YYYY-MM-dd hh-mm-ss").format(new Date())+".txt";
    File file=new File(string);
    if(!file.exists()){  //创建新的文件
        boolean flag=file.createNewFile();
        System.out.println(flag?"yes":"no");
    }
    FileWriter writer=new FileWriter(string,true);
    writer.write("第一条记录\n");  //追加文件内容
    writer.close();
    
    FileReader fileReader=new FileReader(string);
    char[] buf=new char[1024];
    fileReader.read(buf);    //读取文件
    System.out.println(new String(buf,0,1024));
    fileReader.close();
}

(2)FileOutputStream写入,FileInputStream读取。

public static void the2() throws IOException {
    String string="D:\\txt_file"+"\\"+new SimpleDateFormat("YYYY-MM-dd hh-mm-ss").format(new Date())+".txt";
    FileOutputStream fileOutputStream=new FileOutputStream(string);
    byte[] bytes = new String("字节试试").getBytes("utf-8");
    fileOutputStream.write(bytes);
    FileInputStream fileInputStream=new FileInputStream(string);
    byte[] read=new byte[1024];
    fileInputStream.read(read);
    System.out.println(new String(read));
}

至此完毕!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不会写骚年的代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值