File io 字节字符流

操作文件流时不管字节流还是字符流都按照以下 的方式进行
1.使用File找到一个文件
2.通过File对象去实例化字节流和字符流的子类
3.进行字节(字符)的读写操作
4.关闭文件流

一、字节流 inputStream outputStream

package FileText;
/**
 * 体会字节流的输入和输出
 * int read(byte buffer[]);----------试图读取buffer.length个字节到buffer中,并返回实际成功读取的字节数
 */
import java.io.*;
public class ZiJieStreamText {
public static void main(String[] args) throws IOException {
    File f=new File("c:\\abc\\aabcde.txt");
    System.out.println(f.exists());
    OutputStream out=null;
    try {
        out=new FileOutputStream(f);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //写入字节
    byte[] b="hello world!".getBytes();
    out.write(b);
    out.close();
    //打印字节
    InputStream in=null;
    in=new FileInputStream(f);
    byte b1[]=new byte [1024];
    int i=0;
    i=in.read(b1);
    in.close();
    System.out.println(new String(b1,0,i));
}
}

输出结果为

true
hello world!

字符流 Writer Reader

package FileText;
import java.io.*;
public class ZiFuStreamText {
    public static void main(String[] args) throws IOException {
        File f=new File("c:\\abc\\qwe.txt");//创建一个新的文件
        //写入
    Writer wr=new FileWriter(f);
    String str="i love you";
    wr.write(str);
    wr.close();
    //读出
    Reader re=new FileReader(f);
    char [] x=new char[1024];
    int i=0;
    i=re.read(x);
    System.out.println(new String(x,0,i));
    }
}

结果为

i love you
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值