IO-读写文件

一、用字节流读写文件

1、写文件

	//字节流向文件中写东西
	public static void main(String[] args) throws IOException{
		String name="D:"+File.separator+"sun.txt";
		File f=new File(name);
		OutputStream ou=new FileOutputStream(f);
		String str="红鲤鱼与绿鲤鱼与驴,我是字符流";
		byte[] b=str.getBytes();//字节流
		try {
			ou.write(b);  //输出流
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{
			ou.close();			
		}
		
	}

2、读文件

//用字节流读取文件内容
	public static void main(String[] args) throws IOException{
		String name="D:"+File.separator+"sun.txt";
		File f=new File(name);
		InputStream in=new FileInputStream(f);
		byte[] b=new byte[100];
		in.read(b);
		in.close();
		System.out.println(b);
		System.out.println(new String(b));
		
		
	}


二、用字符流读写文件

1、写文件

 

//字符流写入内容到文本
	public static void main(String[] args) throws IOException {
		String name="D:"+File.separator+"sun1.txt";
		File f=new File(name);
		Writer o =new FileWriter(f);
		String str="红鲤鱼与绿鲤鱼与驴,我是字符流";
		o.write(str);
		o.close();

	}

2、读文件

//用字符流读取内容
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		String name="D:"+File.separator+"sun1.txt";
		File f=new File(name);
		char[] ch=new char[100];
		Reader rd=new FileReader(f);
		rd.read(ch);
		rd.close();
		System.out.println(ch);
		System.out.println(new String(ch));
	}

字符流-字节流

1、字节(byte)是计算机存储数据最小单位,以进制存储。一个汉字占两个字节。

2、字符(char)是计算机使用过程中的符号或英文或数字或汉字。

3、用字节流没有缓冲区,用字符流有缓冲区。(不能马上看到效果)

4、用字符流写,不关闭缓冲流,写不进去。

5、字符流效率高一些,字节流效率低一些。因磁盘中的数据文件都是用字节存储的,一般开始时,字节流更广泛。


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值