首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

求教 字节流中OutputStream.write()中直接写InputStream.read()和通过int变量过渡一些的区别,该怎么解决

2012-09-19 
求教 字节流中OutputStream.write()中直接写InputStream.read()和通过int变量过渡一些的区别学习Java中,看

求教 字节流中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());     } 

热点排行