Java--File字节流实现二进制文件的拷贝

File字节流实现二进制文件的拷贝

其实和拷贝文本文件的方式差不多。
有区别的是单位不一样所使用的流也不一样。

这里概括下:

对于文本文件(.txt,.java,.cpp,c),使用字符流处理
对于非文本文件(.png,.jpg,mp3,mp4,avi,doc,.ppt…),使用字节流处理

使用字节流处理文本文件,是可能出现乱码的


	@Test
    public void  InOutStream() {
        /**
         * 使用字节流处理文本文件,是可能出现乱码的
         */
        FileInputStream fis= null;
        FileOutputStream fos=null;

        try {
            //文件
            File file=new File("123.jpg");
            File file1=new File("456.png");
            //流
            fis = new FileInputStream(file);
            fos=new FileOutputStream(file1);
            //读数据
            byte[] buffer=new byte[5];
            int len;
            while((len=fis.read(buffer))!=-1){
                fos.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭流
            try {
                if(fis!=null)
                    fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(fos!=null)
                    fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

可以将上面的代码修改为以下这种(方便修改):

    public void copyFile(String srcPath,String destPath){
        FileInputStream fis= null;
        FileOutputStream fos=null;

        try {
            //文件
            File file=new File(srcPath);
            File file1=new File(destPath);
            //流
            fis = new FileInputStream(file);
            fos=new FileOutputStream(file1);
            //读数据
            byte[] buffer=new byte[1024];
            int len;
            while((len=fis.read(buffer))!=-1){
                fos.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭流
            try {
                if(fis!=null)
                    fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(fos!=null)
                    fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    @Test
    public void textCopyFile(){
        long start=System.currentTimeMillis();
        String src="C:\\Users\\87627\\Desktop\\123.jpg";
        String dest="C:\\Users\\87627\\Desktop\\456.jpg";
        copyFile(src,dest);
        long end=System.currentTimeMillis();
        System.out.print("花费时间:"+(end-start));
    }

之后我们测试了一下,用字节流去复制文本文件,发现是内容是可以复制的。
(如果文本文件里面有中文…,当读入到内存中查看是出现乱码的)。
所以我们总结出,字节流就类似于“搬运工”,用字节流处理文本文件也是可以的,只不过用字符流会好一些。

发布了49 篇原创文章 · 获赞 0 · 访问量 1432

猜你喜欢

转载自blog.csdn.net/qq_43616001/article/details/104005628