Java I/O流-FileInputStream、FileOutputStream

一、整体代码

    FileStreamDemo.java

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class FileStreamDemo {
    public static void main(String[] arg){

        File f = new File("1.txt");


        //向文件里写如"Hello"字符串.
        try    {
            //要写入的数据转换成字节数组
            byte[] buf = "Hello".getBytes();

            //如果1.txt存在,则删除1.txt里面的内容,文本所有内容变为Hello
            //如果1.txt不存在,在新建1.txt文本,写入Hello
            FileOutputStream out = new FileOutputStream(f);

            out.write(buf);//此时文件才建立

            out.close();
        }catch(Exception e)    {
            System.out.println(e);
        }



        //读取文件中的内容。可在程序中单独使用,不用关心"写"是否存在.
        try {
            //只要f存在就可以读出f的内容,与写操作代码没有关联性.
            FileInputStream in = new FileInputStream(f);

            byte[] buf = new byte[1024];

            int len=in.read(buf);        //从流中读取内容
            String str = new String(buf,0,len);

            System.out.println(str);    //打印f文件的内容.    
        }catch(Exception e)    {
            System.out.println(e);
        }

    }
}

            代码地址: https://github.com/jltxgcy/Demo

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值