zoukankan      html  css  js  c++  java
  • Java学习笔记IO流

      广州疯狂软件学院拥有三大课程体系包括:java课程,android课程,ios课程,本文主要讲述java学习之路IO字节流和字符流的区别,文件的复制,更多java知识,android知识,ios知识,疯狂软件官网持续更新中。

      java学习之路IO字节流和字符流的区别,文件的复制

      字节流和字符流使用非常相似,它们有什么不同喃?

      实际上字节流不会用到缓冲区(内存),是文件本身在操作,而字符流会用到缓冲区,通过缓冲区再来操作文件。

      例子:

      public class OutputStreamDemo7 {

      public static void main(String[] args) throws Exception {

      File f= new File("f:" +File.separator +"a.txt" );

      OutputStream out= new FileOutputStream(f);

      String str= "hello like" ;

      byte b[]= str.getBytes();

      out.write(b);

      //out.close();

      }

      }

      结果在a.txt里面有内容

      public class WriterDemo2 {

      public static void main(String[] args) throws Exception{

      File f= new File("f:" +File.separator +"a.txt" );

      Writer w= new FileWriter(f);

      String str= "hello like" ;

      w.write(str);

      //w.close();

      }

      }

      在a.txt里面没有类容,因为现在内容还在缓冲区中

      public class WriterDemo2 {

      public static void main(String[] args) throws Exception{

      File f= new File("f:" +File.separator +"a.txt" );

      Writer w= new FileWriter(f);

      String str= "hello like" ;

      w.write(str);

      w.flush();

      //w.close();

      }

      }

      可以使用flush()强制输出缓冲区的内容,也叫刷新缓冲区

      补充:什么叫缓冲区

      缓冲区其实就是一段特殊的内存,如果一个程序频繁的访问一个文件,我们就把这个文件先放入缓冲区,加快运行速度

      从上面看来,我们使用字节流比字符流好,因为字节流是文件本身在操作,不存在缓冲区的问题(并且所有的文件在硬盘里都是以字节传输的,存储的)

      文件的复制

      把一个文件的内容复制到另外一个文件

      public class OutputStreamDemo8 {

      public static void main(String[] args) throws Exception{

      File f= new File("f:" +File.separator +"a.txt" );//源文件

      File f1= new File("f:" +File.separator +"b.txt" );

      if (!f1.exists()){

      f1.createNewFile();

      }

      InputStream in= new FileInputStream(f);

      OutputStream out= new FileOutputStream(f1);

      byte b[]= new byte[1024];

      int temp=0;

      while ((temp=in.read())!=-1){

      out.write(temp);

      }

      out.flush();

      in.close();

      out.close();

      }

      }

      结果:b.txt里面有了内容

      疯狂Java培训专注软件开发培训,提升学员就业能力,重点提升实践动手能力。疯狂软件开设了java课程,ios课程,android课程,为你提供一个学习java技能的好机会,疯狂软件特大优惠活动,加疯狂软件微信号(疯狂软件),抢优惠,优惠100元+赠送iOS教材一本 详情请看疯狂java培训官网www点fkjava点org。IT从业着仍是社会所需要的高端人才,广州疯狂软件之力于培养企业所需要的中高端IT人才,让你成为备受企业青睐的人才。

  • 相关阅读:
    poj 3616 Milking Time
    poj 3176 Cow Bowling
    poj 2229 Sumsets
    poj 2385 Apple Catching
    poj 3280 Cheapest Palindrome
    hdu 1530 Maximum Clique
    hdu 1102 Constructing Roads
    codeforces 592B The Monster and the Squirrel
    CDOJ 1221 Ancient Go
    hdu 1151 Air Raid(二分图最小路径覆盖)
  • 原文地址:https://www.cnblogs.com/gojava/p/3442945.html
Copyright © 2011-2022 走看看