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");
    }
  • 相关阅读:
    Ftp、Ftps与Sftp之间的区别
    Previous Workflow Versions in Nintex Workflow
    Span<T>
    .NET Core 2.0及.NET Standard 2.0 Description
    Announcing Windows Template Studio in UWP
    安装.Net Standard 2.0, Impressive
    SQL 给视图赋权限
    Visual Studio for Mac中的ASP.NET Core
    How the Microsoft Bot Framework Changed Where My Friends and I Eat: Part 1
    用于Azure功能的Visual Studio 2017工具
  • 原文地址:https://www.cnblogs.com/zhanyd/p/6186038.html
Copyright © 2011-2022 走看看