一、问题描述
今天闲来无事,写了一个下载网上文件的小工具,但当把网上的mp3文件和mp4文件下载下来之后发现打不开,这就郁闷啦!既然能把文件下载下来就证明 URLConnection是没有问题的。查看文件属性也是可以看到文件大小的,这证明数据是有的。很显然是文件读取或写入的时候出现了问题。
于是我做了一个测试:
import java.io.*; public class FileOutputStreamTest{ public static void main(String[] args) throws IOException{ try{ FileInputStream fis = new FileInputStream("Test.txt"); byte[] bbuf = new byte[5]; int hasRead=0; FileOutputStream fos = new FileOutputStream("result.txt"); while ((fis.read(bbuf)) != -1){ fos.write(bbuf); } } catch(IOException e){ e.printStackTrace(); } } }
FileOutputStreamTest.java
测试文件Test.txt数据为: abcdef
运行结果result.txt数据为:abcdefbcde
显然这不是我想要的结果,问题出现的原因是read(byte[])读取一次数据之后,下次在读取不会清除上次读取的内容,而只是进行简单的替换。由于最后一次读取时读到的根本不够5个字节,只读取了1个字节,所以第二次读取时bbuf中的数据为fbcde。
二、问题解决
想写入正确的数据只需要进行一点修改即可,话不多说,直接上代码:
import java.io.*; public class FileOutputStreamTest{ public static void main(String[] args) throws IOException{ try{ FileInputStream fis = new FileInputStream("Test.txt"); byte[] bbuf = new byte[5]; int hasRead=0; FileOutputStream fos = new FileOutputStream("result.txt"); while ((hasRead = fis.read(bbuf)) != -1){ fos.write(bbuf,0,hasRead); } } catch(IOException e){ e.printStackTrace(); } } }
FileOutputStreamTestUpdate.java
通过记录每次读取了多少个字节,然后就写入多少个字节,这样一定不会错。