zoukankan      html  css  js  c++  java
  • java 将一张图片拷贝到另外一个地方。(IO流)

    package com.beiwo.inputstream;
    
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    public class lianxi {
    
        /**
         * @param args
         * 练习题: 将一张图片拷贝到另外一个地方。
         * @throws IOException
         */
        public static void main(String[] args) throws IOException {
            // TODO 自动生成的方法存根
            String str1 = "C:\Users\cdlx2016\Desktop\1\12字方针.png";
            String str2 = "C:\Users\cdlx2016\Desktop\2\12字方针.png";
    //        copyFile1(str1, str2);
    //        copyFile2(str1, str2);
            copyFile3(str1, str2);
            
        }
        // 方法一
        public static void copyFile1(String srcPath, String destPath) throws IOException {
            // 打开输入流
            FileInputStream fis = new FileInputStream(srcPath);
            // 打开输出流
            FileOutputStream fos = new FileOutputStream(destPath);
            
            // 读取和写入信息
            int len = 0;
            while ((len = fis.read()) != -1) {
                fos.write(len);
            }
            
            // 关闭流  先开后关  后开先关
            fos.close(); // 后开先关
            fis.close(); // 先开后关
            
        }
        // 方法二
        public static void copyFile2(String srcPath, String destPath) throws IOException {
            
            // 打开输入流
            FileInputStream fis = new FileInputStream(srcPath);
            // 打开输出流
            FileOutputStream fos = new FileOutputStream(destPath);
            
            // 读取和写入信息
            int len = 0;
            // 创建一个字节数组,当做缓冲区
            byte[] b = new byte[1024];
            while ((len = fis.read(b)) != -1) {
                fos.write(b);
            }
            
            // 关闭流  先开后关  后开先关
            fos.close(); // 后开先关
            fis.close(); // 先开后关
            
        }
        // 方法三
        public static void copyFile3(String srcPath, String destPath) throws IOException {
            
            // 打开输入流
            FileInputStream fis = new FileInputStream(srcPath);
            // 打开输出流
            FileOutputStream fos = new FileOutputStream(destPath);
            
            // 读取和写入信息
            int len = 0;
            // 创建一个字节数组,当做缓冲区
            byte[] b = new byte[1024];
            while ((len = fis.read(b)) != -1) {
                fos.write(b, 0, len);
            }
            
            // 关闭流  先开后关  后开先关
            fos.close(); // 后开先关
            fis.close(); // 先开后关
            
        }
    
    }
  • 相关阅读:
    day34-python-异常
    day33-python-反射、内置方法、元类、 属性查找
    day31/32待补
    day30-mixin、重载、多态、绑定与非绑定方法、内置函数
    day29-python-property、继承、属性查找、多继承带来的菱形问题
    day28-python-封装
    day27-python-面向对象介绍、实现面向对象编程、查找顺序
    luffy项目
    oc基本数据类型
    iOS 入门了解
  • 原文地址:https://www.cnblogs.com/Liang-Haishan216/p/6134468.html
Copyright © 2011-2022 走看看