zoukankan      html  css  js  c++  java
  • java读写文件小心缓存数组

    一般我们读写文件的时候都是这么写的,看着没问题哈。
     
    public static void main(String[] args) throws Exception {
     
    FileInputStream fileInput = new FileInputStream("e://test1.txt");
    FileOutputStream fileOutput = new FileOutputStream("e://test2.txt");
     
    byte[] buffer = new byte[4];
    while(fileInput.read(buffer) != -1){
    fileOutput.write(buffer);
    System.out.println(new String(buffer));
    }
     
    fileInput.close();
    fileOutput.close();
    System.out.println("complete");
     
    }
     
     
     
    写的文件多了234.。。。这是为什么呢。。。
     
     
     
    text1.txt里面的内容为“中国12345”,一共占9个字节。
    byte[]数组长4个字节,循环第三次的时候只读取一个字节,但是第二次循环遗留下来的数据
    还在数组里面,并没有清空。
     
     
     
    所以正确的写法如下:
    byte要初始化一下
     
    public static void main(String[] args) throws Exception {
     
    FileInputStream fileInput = new FileInputStream("e://test1.txt");
    FileOutputStream fileOutput = new FileOutputStream("e://test2.txt");
     
    byte[] buffer = new byte[4];
    while(fileInput.read(buffer) != -1){
    fileOutput.write(buffer);
    System.out.println(new String(buffer));
    buffer = new byte[4];
    }
     
    fileInput.close();
    fileOutput.close();
    System.out.println("complete");
     
    }
     
     
     
    后来发现这样更好:
    public static void transFile() throws Exception{
     
    FileInputStream fileInput = new FileInputStream("e://test1.txt");
    FileOutputStream fileOutput = new FileOutputStream("e://test2.txt");
     
    byte[] buffer = new byte[4];
    int count = 0;
    while((count = fileInput.read(buffer)) != -1){
    fileOutput.write(buffer,0,count);
    }
     
    fileInput.close();
    fileOutput.close();
    System.out.println("complete");
    }
  • 相关阅读:
    [bzoj1576] [Usaco2009 Jan]安全路经Travel
    [坑][poj2396]有上下界的最大流
    bzoj1458 士兵占领
    [Ahoi2013]差异
    bzoj2424 [HAOI2010]订货
    bzoj1741 [Usaco2005 nov]Asteroids 穿越小行星群
    bzoj2251 [2010Beijing Wc]外星联络
    bzoj1977 [BeiJing2010组队]次小生成树 Tree
    bzoj2729 [HNOI2012]排队
    bzoj1925 [Sdoi2010]地精部落
  • 原文地址:https://www.cnblogs.com/zhanyd/p/6186038.html
Copyright © 2011-2022 走看看