• 技术文章 >java >java基础

    Java中IO流复制文件的方法

    小妮浅浅小妮浅浅2021-05-11 09:27:15原创3227

    本教程操作环境:windows7系统、java10版,DELL G3电脑。

    1、使用FileInputStream、FileOutputStream完成文件的复制

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    public void fileCapy(String src, String dest) {

        FileInputStream fis = null;

        FileOutputStream fos = null;

     

        try {

            fis = new FileInputStream(new File(src));

            fos = new FileOutputStream(new File(dest));

            byte[] bytes = new byte[1024];

            int length;

            while ((length = fis.read(bytes)) != -1) {

                fos.write(bytes, 0, length);

            }

        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            if (fos != null) {

                try {

                    fos.close();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

             

            if (fis != null) {

                try {

                    fis.close();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

        }

    }

    2、使用FileReader、 FileWriter完成文本的复制(对于非文本文件, 只能使用字节流)

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    public void textCapy(String src, String dest) {

        FileReader fr = null;

        FileWriter fw = null;

     

        try {

            fr = new FileReader(new File(src));

            fw = new FileWriter(new File(dest));

            char[] chars = new char[1024];

            int length;

            while ((length = fr.read(chars)) != -1) {

                fw.write(chars, 0, length);

            }

        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            if (fw != null) {

                try {

                    fw.close();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

     

            if (fr != null) {

                try {

                    fr.close();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

        }

    }

    以上就是Java中IO流复制文件的方法,希望能对大家有所帮助。更多Java学习指路:Java基础

    专题推荐:java io流
    上一篇:java类加载器如何理解? 下一篇:Java对象流实现序列化的类

    相关文章推荐

    • java中ordinal有什么用?• java反射生成对象的方法• java如何访问成员变量• java使用ParameterizedType实现泛型• java对象创建过程是什么• java类加载器如何理解?

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网