zoukankan      html  css  js  c++  java
  • IO流常见错误--Java学习

    需求:使用IO流将一个文件的内容复制到另外一个文件中去

    文件"good boy.txt"位于D盘根目录下,要求将此文件的内容复制到c:\myFile.txt中

    代码:

    import java.io.*;

    public classInputAndOutputFile{

      public static void main(String[]args){

        FileInputStream fis=null;

        FileOutPutStream fos=null;

        try{  //1.创建输入流对象,负责读取D:/good boy.txt文件

          fis=new FileInputStream("D:/good boy.txt");

          //2.创建输出流对象

          fos=new FileOutputStream("C:/myFile.txt",true);

          //3.创建中转站数组,存放每次读取的内容

          byte[] words=new byte[1024];

          //4.通过循环实现文件读写

          inte len=-1;

          while((len=fis.read(words))!=-1){

          fos.write(words,0,len);

          }

          //5强制清理缓冲区

          fos.flush();

          System.out.println("复制完成,请查看文件!");

        }catch(FileNotFoundExcepton e){

          e.printStackTrace();

        }catch(IOException e){

          e.printStackTrace();

        }finally{
        //6.关闭流

        try{

          fis.close();

          fos.close();

        }catch(IOException e){

          e.printStackTrace();

        }

      }

    }

    常犯错误出现在while循环写入的地方:

    错误代码:

    while((fis.read())!=-1){    //错误之处在这里:此时fis.read();已实现第一次读写,所以words中缓存的字符就少了第一位,导致结果错误。
      fis.read(words);//读取文件

      fos.write(words,0,words.length);//写入文件

    }

     在学习java,但是开发工具不全的朋友,可以进群256242993找群主领取哦

  • 相关阅读:
    POJ1486 Sorting Slides 二分图or贪心
    POJ2060 Taxi Cab Scheme 最小路径覆盖
    POJ3083 Children of the Candy Corn 解题报告
    以前的文章
    POJ2449 Remmarguts' Date K短路经典题
    这一年的acm路
    POJ3014 Asteroids 最小点覆盖
    POJ2594 Treasure Exploration 最小路径覆盖
    POJ3009 Curling 2.0 解题报告
    POJ2226 Muddy Fields 最小点集覆盖
  • 原文地址:https://www.cnblogs.com/xsns/p/6520076.html
Copyright © 2011-2022 走看看