I/O 流

本文介绍了Java中进行文件I/O操作的基本方法,包括字节流和字符流的使用。通过实例展示了如何使用FileOutputStream和FileWriter进行文件写入,以及如何使用FileInputStream和FileReader进行文件读取。

I/O

  1. 字节流
    FileInputStream
    FileOutputStream
  2. 字符流
    FileWriter
    FileReader
    写入例子:
    String myContext = “aaaaaaaaaaa”;
    try {
    java.io.File file=new java.io.File(“D:/file/input.txt”);
    //FileWriter fw = new FileWriter(file,true);//使用FileWriter写入
    byte[] contentInBytes = myContext.getBytes();
    FileOutputStream fop = new FileOutputStream(file,true);//使用FileoutputStream写入
    if(!file.exists()) {
    file.createNewFile();
    fop.write(contentInBytes);
    fop.flush();
    fop.close();
    //fw.write(myContext);
    //fw.close();
    }else {
    fop.write(contentInBytes);
    fop.flush();
    fop.close();
    //fw.append(myContext);
    //fw.close();
    }
    }catch(Exception ex) {
    System.out.println(ex.toString());
    }

    读取例子:
    String str = “”;
    File file = new File(“D:/test.txt”);// 指定要读取的文件
    FileReader reader = new FileReader(file);
    // FileInputStream fi = new FileInputStream(file);
    // byte[] bb=new byte[1024];
    char[] bb = new char[1024];
    int n=0;// 每次读取到的字符长度
    while ((n = reader.read(bb)) != -1) { //用FileInputStream时read中的参数为byte
    str += new String(bb, 0, n);
    }
    reader.close();
    //fi.close();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值