字节流和字符流的区别

字节流

字节流主要是操作byte类型数据,以byte数组为准,主要操作类就是OutputStreamInputStream

字节输出流:

 6 public class Test11 {
 7     public static void main(String[] args) throws IOException {
 8         File f = new File("d:" + File.separator+"test.txt");
 9         OutputStream out=new FileOutputStream(f);//如果文件不存在会自动创建,如果要追加的话,在构造方法里加true
10         String str="Hello World";
11         byte[] b=str.getBytes();
12         out.write(b);//因为是字节流,所以要转化成字节数组进行输出
13         out.close();
14     }
15 }

字节输入流:InputStream

 6 public class Test12 {
 7     public static void main(String[] args) throws IOException {
 8         File f = new File("d:" + File.separator+"test.txt");
 9         InputStream in=new FileInputStream(f);
10         byte[] b=new byte[1024];
11         int len=in.read(b);
12         in.close();
13         System.out.println(new String(b,0,len));
14     }
15 }

字符流

在程序中一个字符等于两个字节,那么java提供了ReaderWriter两个专门操作字符流的类。


字符输出流:Writer

Writer本身是一个字符流的输出类,此类的定义如下:

public abstract class Writer extends Object implements AppendableCloseableFlushable

此类本身也是一个抽象类,如果要使用此类,则肯定要使用其子类,此时如果是向文件中写入内容,所以应该使用FileWriter的子类。

FileWriter类的构造方法定义如下:

public FileWriter(File file)throws IOException

字符流的操作比字节流操作好在一点,就是可以直接输出字符串了,不用再像之前那样进行转换操作了。

 6 public class Test16 {
 7     public static void main(String[] args) throws IOException {
 8         File f = new File("d:" + File.separator+"test.txt");
 9         Writer out=new FileWriter(f);
10         String str="Hello World";
11         out.write(str);
12         out.close();
13     }
14 }

字符输入流:Reader

Reader是使用字符的方式从文件中取出数据,Reader类的定义如下:

public abstract class Reader extends Objects implements ReadableCloseable

Reader本身也是抽象类,如果现在要从文件中读取内容,则可以直接使用FileReader子类。

FileReader的构造方法定义如下:

public FileReader(File file)throws FileNotFoundException

以字符数组的形式读取出数据:

 6 public class Test18 {
 7     public static void main(String[] args) throws IOException {
 8         File f = new File("d:" + File.separator+"test.txt");
 9         Reader input=new FileReader(f);
10         char[] c=new char[1024];
11         int len=input.read(c);
12         input.close();
13         System.out.println(new String(c,0,len));
14     }
15 }


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值