java字符流和字节流

来源:互联网 发布:仿趣分期商城源码 编辑:程序博客网 时间:2024/06/04 18:23

java io中的流分为字节流和字符流

字节流:

字节流主要用的输入输出有两个类:InputStream,OutputStream,整两个类是抽象类,我们需要用到他们的子类:FileInputStream,FileOutputStream,而他们的读写的方法writer,read需要传递的是byte类型的数值。做的小Demo如下,为了让代码清晰,直接throws Exceptions

@Testpublic void test() throws Exception {File f=new File("d:/aaa.txt");String str="你好世界";//这个true的作用是在如果源文件已经存在,则在文件中追加新的字符OutputStream os=new FileOutputStream(f,true);byte b[]=str.getBytes();//下面是write的重载可以直接传入数组,也可以一个一个传递                      os.write(b);for(int i=0;i<b.length;i++){os.write(b[i]);}os.close();}

 

@Testpublic void test()throws Exception{File f=new File("d:/aaa.txt");InputStream is=new FileInputStream(f);byte b[]=new byte[(int)f.length()];int temp=0;int len=0;while((temp=is.read())!=-1){b[len]=(byte)temp;len++;}System.out.println(new String(b,0,len));is.close();}


字符流:

字符流的输入输出主要用到两个类:Writer,Reader,同样的,这两个是抽象类,我们的实现需要他的两个子类FileWriter,FileReader,他们的读写方法write传递的参数是char或者String类型,而read传递是char类型,小demo如下:

@Testpublic void test1()throws Exception{File f=new File("d:/aaa.txt");Writer w=new FileWriter(f);String str="hello world你好世界";w.write(str);w.close();}@Testpublic void test2()throws Exception{File f=new File("d:/aaa.txt");Reader reader=new FileReader(f);char[] c=new char[(int)f.length()];reader.read(c);System.out.println(new String(c,0,(int)f.length()));}


查询api会发现FileWriter,FileReader并不是直接继承Writer和Reader,而是OutputStreamWriter和InputStreamReader,而这两个玩意是负责字符流和字节流之间的转换,demo如下:

@Testpublic void test1()throws Exception{File f=new File("d:/aaa.txt");Writer writer=new OutputStreamWriter(new FileOutputStream(f));String str="你好世界";writer.write(str);writer.close();}@Testpublic void test2()throws Exception{File f=new File("d:/aaa.txt");Reader reader=new InputStreamReader(new FileInputStream(f));char c[]=new char[(int)f.length()];int len=reader.read(c);reader.close();System.out.println(new String(c,0,len));}


字符流和字节流归根到底还是通过字节流操作文件,字符流先向将数据放入缓存,在从缓存中把数据放入文件。
 

原创粉丝点击