现在的位置: 首页 > 综合 > 正文

Java输入输出(3)–OutputStream和Writer

2018年04月06日 ⁄ 综合 ⁄ 共 973字 ⁄ 字号 评论关闭

1.使用FileOutputStream实现复制

   public class FileOutputStreamTest

  {

     public static void main(String[] args) throws IOException

    {

       FileInputStream fis = null;

       FileOutputStream fos = null;

      try

      {

        fis = new FileInputStream("FileOutputStreamTest.java");

       fos = new FileOutputStream("newFile.txt");

       byte[] bbuf = new byte[32];

       int hasRead = 0;

       while((hasRead = fis.read(bbuf))>0)

       {

           fos.write(bbuf,0,hasRead);

       }

      }

    catch(IOException ioe)

    { 

     ioe.printStackTrace();

   }

   finally

   {

     if(fis != null)

     {

      fis.close();

    }

    if(fos != null)

    {

      fos.close();

    }

   }

    }

  }

 

2.直接输入字符串内容,使用Writer会有更好地效果

  public class FileWriterTest

{

   public static void main(String[] args)  throws IOException

   {

      FileWriter  fw = null;

      try

     {

       fw = new FileWriter("poem.txt");

       fw.write("锦瑟  -   李商隐 \r\n");

       fw.write("锦瑟无端五十弦,一弦一柱思华年。\r\n");

     }

    catch(IOException  ioe)

  {

     ioe.printStackTrace();

   }

  finally

  {

    if(fw != null)

    {

    fw.close();

    }

  }

   } 

}

抱歉!评论已关闭.