先上代码
1 2 3 4 5 6 7 | FileOutputStream outputStream = new FileOutputStream( "data.txt" ); byte [] bytes = new byte [ 1024 ]; int num = 0 ; while ((num=fileInputStream.read(bytes)) != - 1 ){ outputStream.write(bytes, 0 ,num); } outputStream.close(); |
这段代码简单的把读取的数据写入data文件中,没什么问题,假如换一种写入方式,如下
1 2 3 4 5 6 7 | FileOutputStream outputStream = new FileOutputStream( "data.txt" ); byte [] bytes = new byte [ 1024 ]; int num = 0 ; while ((num=fileInputStream.read(bytes)) != - 1 ){ outputStream.write(bytes); } outputStream.close(); |
如果读取的文件大小超出1024个字节大小就会出现问题,最终写入的文件大小要大于读取的源文件大小;
这个问题有两个方面造成的
第一个是在读取的方法上read;
第二个是写入的方法write;
理想化来说,有两种解决方案,
第一种:直接读取一整个文件,不进行长度的限制,例如byte[] length = new byte[fileInputStream.available()];当然这种方式自己测测还行,业务环节肯定不行;
第二种:写入方法进行指定长度的写入,
到此,问题是解决了,但是为什么出现这个问题呢,根本原因是什么呢;
通过代码测试
1 2 3 4 5 6 7 | FileInputStream fileInputStream = new FileInputStream( "clone.txt" ); byte [] bytes = new byte [ 8 ]; while (fileInputStream.read(bytes) != - 1 ){ String s = new String(bytes); System.out.println(s); System.out.println( "---------------" ); } |
发现,指定长度为8字节,文件大小为26字节的话,在读取到第24字节的时候发现没读完,继续读,再读2字节,发现读完了,但是你规定了定长啊,那么会继续读取6字节的内容,这个内容从哪来呢,就是从已读取2字节的内容向前数6个字节,出现多读的情况,这就是为什么如果不规定写入长度的时候,程序会给文件多写内容的原因