日期:2014-05-20  浏览次数:20807 次

求教 字节流中OutputStream.write()中直接写InputStream.read()和通过int变量过渡一些的区别
学习Java中,看到字节流的时候按照书上的介绍自己写了一段代码,结果运行后保存的文件是错的,
Java code

    public static void backup(File f01,File f02)throws Exception
    {
//        File f01 = new File(sourcePath);
//        File f02 = new File(path);
        int temp=0;
        FileInputStream fis = new FileInputStream(f01);
        FileOutputStream fos = new FileOutputStream(f02);
        while(fis.read()!=-1)
        {
            fos.write(fis.read());        
        }


再看书上的代码:
Java code

    public static void backup(File f01,File f02)throws Exception
    {
//        File f01 = new File(sourcePath);
//        File f02 = new File(path);
        int temp=0;
        FileInputStream fis = new FileInputStream(f01);
        FileOutputStream fos = new FileOutputStream(f02);
                while((temp=fis.read())!=-1)
        {
            fos.write(temp);            
        }


唯一的区别就是write方法的参数,我是直接写了InputStream.read()方法了,书上是通过一个int变量过渡了一下。但是就是这一些过渡,就决定了我保存文件失败了。 既然InputStream.read()返回值是int,为什么不能直接使用,还必须得用个变量过渡一下呀,求各位大侠帮忙解惑一下,3Q。

------解决方案--------------------
read方法是从此输入流中读取下一个数据字节,楼主的做法数据必然会导致错误(读了2次)
------解决方案--------------------
while(fis.read()!=-1)
{
fos.write(fis.read());
}


fis.read()执行了2边 判断里就读了一个字节 fos.write(fis.read())里读到的是下一个字节

------解决方案--------------------
Java code
while(fis.read()!=-1)
  {
  fos.write(fis.read());   
  }