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");
    }
  • 相关阅读:
    python中函数部分简介与定义(二)
    python中函数部分简介与定义(一)
    db2 不允许在自动存储器表空间上执行 SET TABLESPACE CONTAINERS 命令。的解决办法
    JQuery中$.ajax()方法参数详解
    jquery post 同步异步总结
    js设置height随窗口大小改变
    关于POI的系统整理
    POI 实现导出excel表
    转载>>JQuery EasyUI datagrid 合并表头处理
    iframe标签用法详解(属性、透明、自适应高度)
  • 原文地址:https://www.cnblogs.com/zhanyd/p/6186038.html
Copyright © 2011-2022 走看看